I'm writing a web application with Java Play, and the idea is to have a websocket connect to the server, send a bunch of "live"-data in JSON and have another websocket connect to the server and collect the data. I am trying to implement the observer pattern here, so the server will send data whenever it's updated. I can't seem to get it to work.
So I guess I am asking how to implement the Observer Pattern within a Java Play application.
I have tried putting this code in the onStart-method, but I keep getting InstantiationException, which I'm guessing is because the objects are instantiated when a WebSocket connects.
WSocket socket = new WSocket(); //Observable
Listener listener = new Listener(socket); //Observer
Any tips will be appreciated!
Correct me if I am wrong but I think you are overengineering things. If I understand correctly, you want that the data which is sent from one WebSocket connection is populated to the other active WebSocket connections.
If you are using callbacks in Play, when the WebSocket
is ready, you get both in
and out
channels.
What you can do is to collect all out
channels in some List
and whenever you get some message you just broadcast this message to all of the out
channels you have collected.
And if you have time consider rewriting the handling of WebSocket connections with Akka actors - it is easier and more stable (and also fun ;)