Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference? .on "connect" vs .on "connection"

I'm having difficulty understanding the difference between:

io.on('connection', function (){ });

io.on('connect', function,(){ });

May be quite a primitive question, however I was unable to find clear documentation about it. Would love to learn the difference.

like image 743
Mia Avatar asked Oct 14 '14 02:10

Mia


People also ask

What is the difference between Connect and connection?

(Noun) Connection = relationship between a two things. (Verb) Connect = join together 2 things. Connect 2 things together.

Does Socket IO reconnect automatically?

In the first case, the Socket will automatically try to reconnect, after a given delay.

How do you check if a Socket is connected or not online?

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

How do I remove a Socket IO connection?

click(function(){ socket. disconnect(); });


3 Answers

These are different names of the same thing. As written in socket.io docs:

Event: connection is synonym of Event: connect. Which connect fired upon a connection from client.

like image 170
טל עדס Avatar answered Oct 19 '22 05:10

טל עדס


From naming:

io.on('connection', function (socket) { }); is called directly after the connection has been opened. io.on('connect', function () { }); is called directly before the connection will be opened.

but on quick reading code (https://github.com/Automattic/socket.io/blob/master/lib/socket.js) it looks like the event name connect is emitted after the connection has been opened and there is no event named connection.

like image 34
mabe.berlin Avatar answered Oct 19 '22 06:10

mabe.berlin


I agree with mabe.berlin's idea about the order of these events.

Run:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
    console.log('connection',socket.id);
    io.on('connect',function (socket) {
        console.log('conenct',socket.id);
    });
});
http.listen(1111);

And you will get something like:

connection 6Song1KpSUoUkKgPAAAA

But if you try

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connect',function (socket) {
    console.log('conenct',socket.id);
    io.on('connection', function(socket){
        console.log('connection',socket.id);
    });
});
http.listen(1111);

You are supposed to get something like:

conenct pSlSKNaabR2LBCujAAAA
connection pSlSKNaabR2LBCujAAAA

It proves that socket.io will process connect first then connection.

like image 40
suicca Avatar answered Oct 19 '22 06:10

suicca