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.
(Noun) Connection = relationship between a two things. (Verb) Connect = join together 2 things. Connect 2 things together.
In the first case, the Socket will automatically try to reconnect, after a given delay.
You can check the socket. connected property: var socket = io. connect(); console.
click(function(){ socket. disconnect(); });
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.
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With