Need to send information between Java application and web page

I have a multiplayer game that works fine on sockets, but I'm interested in adding a viewer (and chat) via a webpage 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 websockets be used? Are they compatible with regular sockets? What other methods could I use? (I would rather not use database polling)

+3


source to share


1 answer


You can use httpserver in your Java application to exchange information. It's pretty simple - just a few lines of code. Of course, your computer must be accessible to other computers with a web browser.

This is one of the ways the client communicates with the server. If you want two-way communication, you still need to follow the http rules (not because of Java, but because you are using the browser as a client).



That's what I'm doing. In the opening JavaScript connection, it could be anything - AJAX, an image, a JavaScript source for a new dynamic JavaScript object (which is what I do). Server side open but don't close the connection - wait until you have something to send. When you have it, send it. The browser will have it at this point. Simply and easily. However, there is a necessary trick: if the server waits long (2 minutes) the browser closes the connection. In this case, your JavaScript should be ready and repeat the same request. And repeats it. On the server side, your connection will be closed, but a new one will be open and it will wait when you're ready. Another trick is when you make a new request from the browser side - don't forget about the cache. To avoid having the same response from the cache, add something unique to the request.For example the current time as a parameter.

+1


source







All Articles