I have a multi-player game that works normally over sockets, but I am interested in adding a spectator view (and chat) via a Web page and Javascript.
I just need to send a few bytes of information every few seconds to the webpage, and then of course chat messages to and from the game server (they will have to be logged in to send messages).
Can I use websockets? Are they compatible with regular sockets? What other methods could I use? (I'd prefer not to use database polling)
You can use httpserver inside your Java application to share information. It's pretty simple - just few lines of code. Of course your computer should be available for other computers with web browser.
That's one way communication client to server. If you need 2-way communication you still need to obey http rules (not because of Java but because you use browser as the client).
Here what I do. In JavaScript open connection, It could be anything - AJAX, image, JavaScript source for new JavaScript dynamic object (that's what I do). On the server side open but don't close connection - wait till you have something to send. When you have it - send it. Browser will have it at this exact moment. Plain and simple. However, there is necessary trick: if server waits to long (2 minutes) browser closes the connection. In this case your JavaScript should be ready and make the same request again. And os it repeats. On server side your connection will be closed but new one will be opened and it will wait when you are ready. One more trick - when you do new request from browser side - don;t forget about cache. To not have the same answer from cache add something unique to the request. For example current time as parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With