Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

io.on('connection',...) vs io.sockets.on('connection',...)

I am using socket.io and the Mean stack for a web app. I started the server for socket on 3006 port..

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

Both of these seem to work on connection.

io.on('connection', function (socket) {
    console.log('Socket succesfully connected with id: '+socket.id);
});

and...

io.sockets.on('connection', function (socket) {
   console.log('Socket succesfully connected with id: '+socket.id);
});

What is the difference between io.on and io.sockets.on and which one should I use on first time connection..?

Though socket.on npm page uses io.on why is it working for io.sockets.on

like image 872
Srinath Avatar asked Jun 17 '14 14:06

Srinath


People also ask

What is the difference between IO and Socket?

In your code example, io is a Socket.IO server instance attached to an instance of http. Server listening for incoming events. The socket argument of the connection event listener callback function is an object that represents an incoming socket connection from a client.

What is the difference between Socket.IO and WebSocket?

Key Differences between WebSocket and socket.ioIt provides the Connection over TCP, while Socket.io is a library to abstract the WebSocket connections. WebSocket doesn't have fallback options, while Socket.io supports fallback. WebSocket is the technology, while Socket.io is a library for WebSockets.

What is Socket.IO connection?

Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection.

How do you check if socket IO client is connected or not?

You can check the socket. connected property: var socket = io. connect(); console.


1 Answers

The default namespace that Socket.IO clients connect to by default is: /. It is identified by io.sockets or simply io (docs).

This example copied from the documentation:

// the following two will emit to all the sockets connected to `/`  io.sockets.emit('hi', 'everyone');  io.emit('hi', 'everyone');           // short form 

I assume it is the same for 'on', as it is for 'emit': using 'io.sockets' is equivalent to using 'io' only, it's just a shorter form.

To “namespace” your sockets, means assigning different endpoints or paths (which can be useful).

From an answer to this SO question:

"Socket.io does all the work for you as if it is two separate instances, but still limits the information to one connection, which is pretty smart."

like image 160
AJO_ Avatar answered Oct 04 '22 16:10

AJO_