[Turn] Do you know the difference between the connect event and the connection event in socket.io?

socket.ioThere are two connection events on the server side . One is .on('connect')and the other is .on('connect').

The official website does not explain the difference between the two events.

So what is the difference between these two events? There seems to be no difference in use?

socket.ioThe author conducts experiments on version 2.0.4 .

base case

This code sets up a simplest socket.io server, listening on port 1111.

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);

After the client connects, the log is as follows:

conenct 8uBVxwqym7pxsJANAAAA
connection 8uBVxwqym7pxsJANAAAA

As you can see, both respond to the connection event normally. However, we find that connectthe event seems to be preceded by the connectionevent because its log comes first!

Let's verify our conjecture.

Exchange position: connect set connection

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);

We found that the order of the output log has not changed:

conenct pSlSKNaabR2LBCujAAAA
connection pSlSKNaabR2LBCujAAAA

This means that the connection event can still be fired after the connect event.

Exchange position: connection set connect

After we want to verify the connection event, the connect cannot be fired.

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);

The output results are in line with expectations. We can find that after the connection event is triggered, the connect event is not triggered!

connection 1QCOp0Y0fuH2xG-LAAAA

in conclusion

connectSimilar connectionto the event function, but is triggered at a different time. connectBefore connetion.

connectis triggered as soon as there is a connection, and connectiononly after the connection is fully established.

Generally, just like the example on the official website, you can use the connectionevent directly.

But in order to maintain consistency with the front end, connectit is not impossible to use all events.

References:
https://socket.io/get-started...
https://stackoverflow.com/que...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325555355&siteId=291194637