3

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)

1
  • Websockets are not compatible with regular sockets. They are a very different beast. I recommend that you learn about java servlets and use http requests. Commented Jun 3, 2015 at 22:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I get how I sent from Javascript to Java (with http requests), but what about the other way around? Do I use server-sent events and one ongoing connection? How can I tell, from Java, if the browser window is closed, and that I need to terminate?
http protocol is stateless and interrupt able but there so many tricks. I'll update answer right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.