Iḿ doing a socket.io, Node project and I dont understand the squence of calling the functions. I have the following code for the server:
//Socket setup
var io = require('socket.io')(http);
var c= [];
//functions
function y(clientid){
console.log('Show clients: '+c)
}
var x = function(socketid, fn) {
var customid = y(socketid)
console.log('x is calling');
fn(customid);
};
io.on('connection', (socket) => {
console.log('User connected with %s', socket.id);
socket.on('storeClientInfo', function (data) {
console.log('Thought this would be the first call')
//clients.push here
});
x(socket.id, function(socketid, ) {
socket.emit('random', {
test1: 'test1',
test2: 'test1'
});
});
});
My code for the client is:
var socket = io();
socket.on('connect', function () {
socket.emit('storeClientInfo', { customId:Math.floor(Math.random() * 100 + 1 )});
});
socket.on('random', function (message) {
//display message here
});
My console log outputs:
User connected with MH0WD_zNzVOzi_6oABAB
Show clients:
x is calling
Thought this would be the first call
Now my question is: Why at first the method gets called an not the socket.on('storeClientInfo')?
Greetings
Here's the sequence of events in time:
io.on('connection', ...)
event handler.connect
and random
events on that socket. Note: This socket is NOT yet connected. It's in the process of trying to connect.connection
event on the server is called.console.log('User connected with %s', socket.id);
and see User connected with MH0WD_zNzVOzi_6oABAB
in the console.socket.on('storeClientInfo', ...)
event handler for that newly connected socket.x(socket.id, ...)
which then calls y(...)
which outputs Show clients:
.y()
finishes executing and then x()
outputs x is calling
.connect
event and you send a message to the server with socket.emit('storeClientInfo', ...)
.storeClientInfo
event and the socket.on('storeClientInfo', ...)
event handler runs and you output Thought this would be the first call
.Perhaps the part you didn't know about is that in the client, this code:
var socket = io();
is asynchronous. This just starts the process of connecting. The socket is not connected yet when this returns. There is a socket.io socket
object available for you to register event handlers on, but it is not yet connected to the server.
That's why you have to register an event handler for the connect
event to see when it actually completes the connection.