Mia
Mia

Reputation: 6531

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.

Upvotes: 26

Views: 8792

Answers (3)

טל עדס
טל עדס

Reputation: 91

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

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

Upvotes: 9

suicca
suicca

Reputation: 81

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.

Upvotes: 8

mabe.berlin
mabe.berlin

Reputation: 1073

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.

Upvotes: 7

Related Questions