Good Beginners Tutorial to Socket.Io

Good beginners tutorial to socket.io?

To start with Socket.IO I suggest you read first the example on the main page:

http://socket.io/

On the server side, read the "How to use" on the GitHub source page:

https://github.com/Automattic/socket.io

And on the client side:

https://github.com/Automattic/socket.io-client

Official tutorial
https://socket.io/get-started/chat

What is an example of the simplest possible Socket.io example?

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

index.html

<!doctype html>
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();

socket.on('welcome', function(data) {
addMessage(data.message);

// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));

function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');

el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>

app.js

var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });

socket.on('i am client', console.log);
});

app.listen(3000);

How to start socket.io learning?

This is the tutorial I remember following. It's nicely broken down and the stages are well explained - and it leads to a working example (open lots of browser Windows to see it working).

http://code.tutsplus.com/tutorials/real-time-chat-with-nodejs-socketio-and-expressjs--net-31708

tutorial for Express 3.x and socket.io

You can check any 2.x tutorial and change the way to start the server as this post explains:
socket.io.js not found

2.X.X

var app = require('express').createServer();
var io = require('socket.io').listen(app);

app.listen(10000);

3.X.X

var express = require('express')
, http = require('http');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

server.listen(10000);

Socket.io: How to correctly join and leave rooms

Socket.IO : recently released v2.0.3

Regarding joining / leaving rooms [read the docs.]

To join a room is as simple as socket.join('roomName')

//:JOIN:Client Supplied Room
socket.on('subscribe',function(room){
try{
console.log('[socket]','join room :',room)
socket.join(room);
socket.to(room).emit('user joined', socket.id);
}catch(e){
console.log('[error]','join room :',e);
socket.emit('error','couldnt perform requested action');
}
})

and to leave a room, simple as socket.leave('roomName'); :

//:LEAVE:Client Supplied Room
socket.on('unsubscribe',function(room){
try{
console.log('[socket]','leave room :', room);
socket.leave(room);
socket.to(room).emit('user left', socket.id);
}catch(e){
console.log('[error]','leave room :', e);
socket.emit('error','couldnt perform requested action');
}
})

Informing the room that a room user is disconnecting

Not able to get the list of rooms the client is currently in on disconnect event

Has been fixed (Add a 'disconnecting' event to access to socket.rooms upon disconnection)

 socket.on('disconnect', function(){(
/*
socket.rooms is empty here
leaveAll() has already been called
*/
});
socket.on('disconnecting', function(){
// socket.rooms should isn't empty here
var rooms = socket.rooms.slice();
/*
here you can iterate over the rooms and emit to each
of those rooms where the disconnecting user was.
*/
});

Now to send to a specific room :

// sending to all clients in 'roomName' room except sender
socket.to('roomName').emit('event', 'content');

Socket.IO Emit Cheatsheet

user authentication using socket.io

I know this is bit old, but for future readers in addition to the approach of parsing cookie and retrieving the session from the storage (eg. passport.socketio ) you might also consider a token based approach.

In this example I use JSON Web Tokens which are pretty standard. You have to give to the client page the token, in this example imagine an authentication endpoint that returns JWT:

var jwt = require('jsonwebtoken');
// other requires

app.post('/login', function (req, res) {

// TODO: validate the actual user user
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: 123
};

// we are sending the profile in the token
var token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60*5 });

res.json({token: token});
});

Now, your socket.io server can be configured as follows:

var socketioJwt = require('socketio-jwt');

var sio = socketIo.listen(server);

sio.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));

sio.sockets
.on('connection', function (socket) {
console.log(socket.handshake.decoded_token.email, 'has joined');
//socket.on('event');
});

The socket.io-jwt middleware expects the token in a query string, so from the client you only have to attach it when connecting:

var socket = io.connect('', {
query: 'token=' + token
});

I wrote a more detailed explanation about this method and cookies here.

My socket.io and node.js code won't work - why?

socket.broadcast.emit(...) sends to all connected sockets EXCEPT socket. So, it will not send back to the one that originated the message you're responding to. So, if you had multiple clients connected, the other clients would see the messages.

If you intend to send it back to the originating client, then use:

socket.emit(...);

If you intend to send to all connected sockets on the top level namespace, then do:

io.emit(...);


Related Topics



Leave a reply



Submit