Skip to content

Instantly share code, notes, and snippets.

@Rob-pw
Created January 8, 2014 14:11
Show Gist options
  • Save Rob-pw/8317268 to your computer and use it in GitHub Desktop.
Save Rob-pw/8317268 to your computer and use it in GitHub Desktop.
var io = require('socket.io').listen(8080);
//Listen for the connection event to be fired, this is done after a new successful connection is made to a client
//Provides a reference to the opened socket / client, connection specific communication done via ref.
io.sockets.on('connection', function (socket) {
//First, we'll emit (send) a Message Of The Day to our client.
//In this case, the event handle is 'motd' and the data is "Welcome to my server!"
socket.emit('motd', "Welcome to my server!");
//Now we'll add an event handler for the 'message' event, once fired it will call the function
//An object / variable is passed, this contains all of the data sent by the client for that event.
socket.on('message', function(data) {
console.log(data);
});
socket.on('important_message', function(data, callback) {
callback('Roger that');
});
//We'll also wait for the disconnect event, this is fired when either: the client says it's disconnecting, or the client doesn't respond for a given time.
//Connection is upheld using heartbeats, think of it as a more advanced ping system
// Svr - "Are you still there?"
// Cli - "Yep"
// Svr - "Are you still there?"
// Cli - "Yep"
// Svr - "Are you still there?"
// -- waits
// Svr - "Client presumed to have disconnected, fire disconnect event."
socket.on('disconnect', function() {
//No data is returned, and the connection is no longer active, hence one cannot emit on socket.
//socket.broadcast is used to broadcast to all active connections, except the socket that sent it.
//We have passed an object with two properties: message and clientID
//In the background, the passed object is stringified as JSON, then sent
//At the other end, the client parses the JSON string into an object again, hence references are broken and functions cannot be communicated.
socket.broadcast.emit('client_disconnected', {
message : "User: " + socket.id + ", disconnected.",
clientID : socket.id
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment