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

It’s hard for me to understand the difference between:

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

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

Maybe a rather primitive question, however, I could not find clear documentation about this. I would like to know the difference.

+4
source share
2 answers

I agree with the Mayberlin idea of ​​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 should get something like:

conenct pSlSKNaabR2LBCujAAAA
connection pSlSKNaabR2LBCujAAAA

This proves that socket.io will process connectfirst and then connection.

+1
source

On behalf of:

io.on('connection', function (socket) { });called immediately after the connection has been opened. io.on('connect', function () { });called immediately before opening a connection.

(https://github.com/Automattic/socket.io/blob/master/lib/socket.js) , , , connect connection.

0

All Articles