Game Development Reference
In-Depth Information
API calls to send and receive messages are shown in the following code snippet:
connection.send('Hey?');
connection.onmessage = function(e){
var data = e.data;
console.log(data);
}
Sending JSON messages are shown in the following code snippet:
var message = {
'username': 'sumeet2k06',
'comment': 'Trying to tell something about WebSockets'
};
connection.send(JSON.stringify(message));
Understanding the WebSockets server
A regular HTTP server cannot handle WebSockets requests. We need to install
libraries or some external servers to handle requests. There are many WebSocket
servers. Two of them are listed as follows:
phpwebsocket ( https://code.google.com/p/phpwebsocket/ ) for PHP
Socket.IO ( http://socket.io/ ) for Node.js
As our topic uses JavaScript throughout, we would like to work with Node.js and
Socket.IO. Also, Socket.IO offers a very powerful client-side JavaScript library, which
works even if the browser does not support WebSockets.
Using Node.js and Socket.IO for
multiplayer games
Node.js is based on the event-based programming style, where the flow of the
application is determined by the events. It is a new generation style of writing a
scalable server-side code. Unfortunately, this topic is not on Node.js; hence, we
would like to completely keep our focus on Node.js-based HTTP servers and Socket.
IO. For further reading, you can refer to the following links:
Installing Node.js ( http://howtonode.org/how-to-install-nodejs )
Loading node modules ( http://nodejs.org/api/modules.html )
Emitter pattern ( http://nodejs.org/api/all.html#all_events )
Stream ( http://nodejs.org/api/all.html#all_stream )
Our focus in this topic is to discuss two modules of Node.js: HTTP and Socket.IO.
 
Search WWH ::




Custom Search