3
votes

I have a websocket connection setup in my Play application. The function is below, and I'm trying to stream some data in this function.

When the websocket connection is set up and ready to go, I create a while loop that creates random numbers to be sent into the out stream of the websocket to the front end.

These are the things I have observed as I've tested this:

  1. If I comment out the while loop code and only have the first three out.write(...), they all get to the front end as expected.
  2. If I uncomment the while loop code, no messages are received by the front end. Not even the first three out.write(...) that go out if the while loop is commented.

This has me a bit baffled. If the first three out.write(...) messages go out, why do they and the while loop out.write(...) not go out when the while loop is uncommented?

The loop is running as verified through print statements, but the front end does not get any messages. Can we not call 'out.write(...)' in a loop ona websocket?

   public static WebSocket<String> realTimeChartConnection() {
    return new WebSocket<String>() {
        // called when the websocket is established
        public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
            // register a callback for processing instream events
            in.onMessage(new Callback<String>() {
                public void invoke(String event) {
                    System.out.println(event);
                }
            });             
            System.out.println("Websocket Connection ready ...");

            out.write("50");
            out.write("51");
            out.write("60");

            int prev = 50;
            while (true) {
                int y = (int) (prev + Math.random() * 10 - 5);
                if (y < 0)
                    y = 0;
                if (y > 100)
                    y = 100;
                out.write(""+y);
                try {
                    Thread.currentThread();
                    Thread.sleep(30);
                } catch (Exception e) {
                    System.out.println(e.getStackTrace());
                }
            }
        }
    };
}
1

1 Answers

0
votes

I don't have any knowledge of play or scala but as i understand you block a thread of execution.