Repository navigation
SOCKET.IO
It enables real-time, bi-directional communication between web clients and servers.
It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Both components have an identical API.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket) {
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
Sockets work based on events. There are some reserved events, which can be accessed using the socket object on the server side.
These are −
- Connect
- Message
- Disconnect
- Reconnect
- Ping
- Join and
- Leave
The client-side socket object also provides us with some reserved events, which are −
- Connect
- Connect_error
- Connect_timeout
- Reconnect, etc
Now we will be using the message event to pass message from the server to the client. To do this, modify the io.on ('connection', function(socket)) call to include the following −
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io.on('connection', function(socket) {
console.log('A user connected');
//Send a message after a timeout of 4seconds
setTimeout(function() {
socket.send('Sent a message 4seconds after connection!');
}, 4000);
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
- To broadcast an event to all the clients, we can use the io.sockets.emit method.
- Note − This will emit the event to ALL the connected clients (event the socket that might have fired this event).
Socket.IO allows you to “namespace” your sockets, which essentially means assigning different endpoints or paths.
- The root namespace '/' is the default namespace, which is joined by clients if a namespace is not specified by the client while connecting to the server.
- To set up a custom namespace, we can call the ‘of’ function on the server side
Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms.
You can call the join method on the socket to subscribe the socket to a given channel/room.
To leave a room, you need to call the leave function just as you called the join function on the socket.
socket.on('connect_failed', function() {
document.write("Sorry, there seems to be an issue with the connection!");
})