socket.io
There 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.io
The 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 connect
the event seems to be preceded by the connection
event 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
connect
Similar connection
to the event function, but is triggered at a different time. connect
Before connetion
.
connect
is triggered as soon as there is a connection, and connection
only after the connection is fully established.
Generally, just like the example on the official website, you can use the connection
event directly.
But in order to maintain consistency with the front end, connect
it is not impossible to use all events.
References:
https://socket.io/get-started...
https://stackoverflow.com/que...