Advertisement

Wrapping my head around websockets

Started by January 13, 2014 05:08 PM
7 comments, last by Kenny84 10 years, 10 months ago

So, I'm creating an HTML5 game that will require a server. I initially thought that websockets were the same as regular tcp connections, but through the browser, and I have come to find that is not the case.

I'll quickly share what my understanding of how websockets are different here before I get to my question, in case I am wrong.

  • Websockets are essentially a layer on top of tcp
  • They are asynchronous
  • They are event driven
  • Require an http like handshake
  • Message based, rather than a stream of bytes

My issues are coming from the two in red above.

Normally a client would process and input and send a message to the server like "can I move up?" and the server would respond with "yes" or "no". Because the send is asynchronous, I'm not sure how I am going to handle the servers' response.

The fact that they are event driven really confuses me, for the server side of things normally I would create a server something like this:


while(true)
{
    accept new connections
    foreach player in playerlist
             check for incoming messages and respond
    update world
    send any updates to players
}

With websockets the paradigm is completely different and I'm strugglign to figure out how I would create it.

*A quick note, I'm creating this game with libgdx (not sure if it really matters).

Any help would be appreciated, thanks.

All networking is, inherently, asynchronous. If you are using a synchronous API (such as read() and write() on UNIX) then you are letting the OS block your thread for you. This is generally a bad idea, because if there is any stall on the network, your user interface will typically lock up.

Normally a client would process and input and send a message to the server like "can I move up?" and the server would respond with "yes" or "no".


I disagree. This is "blocking RPC" and is pretty much never used in games. Typically, the client knows the game rules just like the server, so the client will just locally check the rules, and if the rules seem OK, the client will locally show the player moving up, and send a message to the server. If the server finds that the movement violated some rule that the client didn't know about, it will then not update the client entity's position, and the client will receive a packet with its own entity back in the old position, and will correct itself.

The specifics may vary a little bit between each game genre/type/implementation, but asking-and-waiting is pretty much never actually used. Informing-and-reacting is the basic pattern of game networking across pretty much all genres, because of the requirement for interactivity and (often) latency compensation.
enum Bool { True, False, FileNotFound };
Advertisement

hplus0606 makes a good point -- most networking is asynchronous otherwise you'd be locking up the machine any time you made even a basic request. That's just a bad idea for many reasons.

That being said, you're also correct that on servers there are typically synchronous and asynchronous socket types available. On a client, however, you should never be able to easily lock up the user's machine!

Because client-side is mostly asynchronous, you need to put your code into event handlers. Here's a sample from Mozilla (but most JavaScript implementations will be similar):


var exampleSocket = new WebSocket("someserver.com");
exampleSocket.onmessage = function (event) {
   console.log(event.data);
}


In practical terms this means that you can't put all of your game actions into a single processing loop (that's actually a bad way to code anyways -- makes it very difficult to upgrade and maintain).

So how can you process game actions? Without knowing specifics, there are two general approaches you can take:

1. Put your game handling code into a single "processGameAction" function (or something similar), and invoke it when you get the response:


exampleSocket.onmessage = function (event) {
   processGameAction();
}


The processGameAction function could create timers to control independent game elements so that game action could continue even between socket messages.

2. Do the same thing as above but instead of calling processGameAction from the event handler, you would set the current game state in the handler and instead keep processGameAction running in an indefinite loop (timer).


var gameState={};
gameState.queue=false;
exampleSocket.onmessage = function (event) {
   gameState.action=event.someData; //Just an example...you need to grab the relevant values yourself...
   gameState.queue=true;
}
 
function processGameAction() {
   if ((gameState==null) || (typeof gameState=="undefined")) {
      return;
   }
   if (gameState.queue==false) {
      return;
   }
   if (gameState.action=="doStuff") {
      //do stuff here
      gameState.queue=false; //Make sure we only process this once after being set!
   }
}
 
window.setInterval(processGameAction,10); //Execute every 10 ms


The "doStuff" part above is, again, up to you. In fact, the gameState object is completely open-ended -- you fill it with the data that you need based on the socket or user interaction events within the game.

The main idea here is that you need to encapsulate your game logic within a function and, at the very least, call that function on a timer in order to create a loop. This also means having to potentially create additional variables to track your loop state, but that's really part and parcel of Object-Oriented(ish) Programming.

Keep in mind that you can create numerous timers -- just make sure to store their IDs (the setInterval function returns this), so that you can stop/restart them when needed. This is a bit more complex than just straight-up procedural loops but it gives your WAY more flexibility without locking up your code (for example, your intervals can be set to trigger at various rates depending on how fast you want the game to move).

on servers there are typically synchronous and asynchronous socket types available


While there are synchronous and asynchronous socket APIs available (on both server and client,) on the server it's even more important to not be synchronous.
If you did any kind of synchronous read on the server, I could open a simple TCP connection, send a single byte, and then send nothing more, and I would stall out your server, effectively preventing it from making progress for anyone else.
Thus, even with the synchronous APIs, you want to use some kind of polling API, such as select(), epoll, or similar, so that you know that the next synchronous call (recv, send, accept) will not actually block.
enum Bool { True, False, FileNotFound };

Thank you for the replies. I guess the asynchronousness (is that a word?) of it shouldn't have confused me as much as it did. In the past I have used non-blocking sockets and actually sent everything asynchronously, except the client -> server message (every client to sever message recieved a synchronous reply). But I guess that won't be a big deal (as you said will help with latency) and in hindsight I probably should have been doing this to begin with.

I'm afraid I'm still somewhat confused on the server side of things. It seems though for websockets a thread is created for every connection, is that correct? I would kind of prefer to have a single thread (with a similar structure that I put above) as opposed to timers as Patrick suggested. It just seems much easier to do everything in one thread and one loop rather than dealing with multiple threads and timers. I don't think performance would be an issue but I could be wrong.

It seems though for websockets a thread is created for every connection, is that correct?


That depends on the specific server you are using.

For example, if you are using node.js with socket.io, then there is only one thread, and each message from each client is delivered to a callback to your program in a reactive fashion.
enum Bool { True, False, FileNotFound };
Advertisement

Multiplayer JavaScript HTML5 Gaming

For Multiplayer HTML5 Gaming Excellence, you may consider leveraging multiplayer fabrics in ImpactJS, MelonJS, Construct2 or Unity. Here are some getting started guides in the realms of specific frameworks. State provides a difficult problem when it comes to making multiplayer games. The problem at hand is keeping track of where each on-screen entity is, including the values for the entity’s attributes. In some situations, it may be ok to have each client blast out information and have the other clients update accordingly. But what if two clients disagree? Who’s right? I typically designate a "Host" device and the connecting players are "Guests". The game "Host" decides who wins in the race.

http://www.pubnub.com/blog/lightweight-multiplayer-html5-games-with-pubnub-and-melonjs/

PubNubMelonJSGame1.jpg

If two clients disagree, then you have to pick a winner. You could pick the client that made the decision on the earliest time step, Or you could pick the client with the lowest-numbered player ID, or the highest-numbered IP address, or something.

That being said, clients making decisions means that your game is open to cheating/hacking. The only way around that is to introduce a server with some model of trust.
enum Bool { True, False, FileNotFound };

Thanks for all the help everybody, I think I've got enough to move forward with. smile.png

This topic is closed to new replies.

Advertisement