• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Kenny84

Wrapping my head around websockets

8 posts in this topic

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.

 

 

 

0

Share this post


Link to post
Share on other sites
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.
2

Share this post


Link to post
Share on other sites

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).

Edited by Patrick B
0

Share this post


Link to post
Share on other sites

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.
0

Share this post


Link to post
Share on other sites

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.

Edited by Kenny84
0

Share this post


Link to post
Share on other sites

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.
0

Share this post


Link to post
Share on other sites

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

Edited by PubNub
0

Share this post


Link to post
Share on other sites
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.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0