chickenman
chickenman

Reputation: 798

How does socket.io get arguments from the client?

I have the following code on the server side:

var io = socket(server);

io.on('connection', function(socket){
    console.log('made socket connection with ID:', socket.id);
});

Here is what I understand.

We make a socket on the server side and pass that (instance?) to io. Then, we say io.on('connection') which is saying listen to the connection event. We also make a callback function to which we are passing socket.

I don't understand the callback function(socket) part. Where are we passing it socket? on the client side I have this

var socket = io.connect('http://localhost:4000');

I get that a connection will be made and it will start listening but how and where are we calling the function form the client side?

Upvotes: 1

Views: 2027

Answers (1)

Amadan
Amadan

Reputation: 198334

We are not calling the callback, and so we are not passing it anything. You can't call a serverside function from the clientside.

The callback is called (and given the argument) by the JavaScript's event loop, as triggered by socket.io library's internals - more specifically, as far as I can see, in Engine.io:

Server.prototype.handshake = function (transportName, req) {
  ...
  self.emit('connection', socket);
  ...
};

This is done through Node's native EventEmitter, which allows you to register a callback for an event (io.on('connection', function(socket) { ... })), and emit the event with data for the callback (self.emit('connection', socket)). The data passed with the event emission is the data received by any callback registered for the event on the emitter object.

Thus, the flow is roughly as follows:

  • Serverside, you register a callback handler for the connection event on the Engine.io object (passed to you by Socket.io's socket function).
  • Clientside, you invoke the connect function. It starts a Websocket request.
  • Serverside, Engine.io receives the Websocket request. It creates a socket object to represent the connection with that particular client, then emits the connection event, with the socket object as accompanying data.
  • The connection event causes all handlers registered for that event to be invoked, and passed the accompanying data (the socket object), your function being among them.

Upvotes: 1

Related Questions