Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ruby0x1/2216624 to your computer and use it in GitHub Desktop.
Save ruby0x1/2216624 to your computer and use it in GitHub Desktop.
Multi-player games in HTML5 : Setting up Socket.io on the server side
//Create and listen for clients on the existing web server
//we created above. app is the express server.
var io = require('socket.io').listen( app );
//We also introduce a UUID library, for unique identifiers.
//Not required, but I find useful.
var UUID = require('node-uuid');
/* Socket.io Configuration */
//Give socket.io a function to configure itself
io.configure(function (){
//We are using XHR polling for mobile browsers.
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
io.set('log level', 1);
//This is taken from the socket.io examples.
io.set('authorization', function (handshakeData, callback) {
callback(null, true); // error first callback style
}); ///set auth
}); ///io.configure
/* Socket.io client connection handler */
io.sockets.on('connection', function (socket) {
//This client can store its server id
socket.serverid = UUID();
//This will send a message to all clients saying that they connected,
//And hand them their serverid for future interactions.
socket.emit('onConnect', { serverid : socket.serverid });
//Each socket has some default handlers you can listen for,
//but any and all events can be listened for. These events are the named
//events sent from emit (like above). Take note that this is set on the socket (the client)
//and not on io (the socket.io library). This means that if you store a list of clients,
//store the socket, and attach per client events onto the socket itself. Like below.
socket.on('error', function(d){
//For now
console.log(d);
}); /// on error
}); /// on connection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment