Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send additional data on socket connection

How to best send additional data upon socket connection?

Client:

socket.on('connect',function(){  //I'd like set some values and pass them up to the node server. }); 

Node.js Server:

io.on('connection', function(client){ //I'd like to get the data here. }); 

For example sending a user name or email address etc.

like image 417
Dan Avatar asked Jan 20 '11 04:01

Dan


People also ask

How much data can you send over WebSocket?

As of v3, socket.io has a default message limit of 1 MB. If a message is larger than that, the connection will be killed.

How many messages per second can socket.io handle?

Both server and client node processes use 95-100% of a CPU core each. So pure throughput looks ok. I can emit 100 messages per second to 100 local clients at 55% CPU usage on the server process.

Is socket.io better than WebSocket?

As said before, Socket.IO can fall back to technologies other than WebSockets when the client doesn't support it. If (for some reason) a WebSocket connection drops, it will not automatically reconnect… but guess what? Socket.IO handles that for you! Socket.IO APIs are built to be easier to work with.


2 Answers

I have a different approach - emit an event right after connecting, with the data:

socket.on('connect',function(){      // Send ehlo event right after connect:     socket.emit('ehlo', data); });  io.on('connection', function(client){     // Receive ehlo event with data:     client.on('ehlo', function(data) {     }); }); 

You can hold a variable/object, and say, when there is no ehlo event with data, the other events are ignored until ehlo is sent.

If this does not satisfy, you can send data right when connecting, I won't copy the code but it is in this answer: https://stackoverflow.com/a/13940399/1948292

like image 44
Daniel W. Avatar answered Oct 09 '22 17:10

Daniel W.


You should send your data either in connect or on create:

var s = io('http://216.157.91.131:8080/', { query: "foo=bar" }); s.connect();  var c = io.connect('http://216.157.91.131:8080/', { query: "foo=bar" }); 

With the new version of socket.io, on server is where the things have been changed:

var io = require('socket.io')(server);  io.use(function(socket, next) {   var handshakeData = socket.request;   console.log("middleware:", handshakeData._query['foo']);   next(); }); 
like image 193
Miquel Avatar answered Oct 09 '22 18:10

Miquel