Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send two variables in one message using Socket.io?

I have a clientid and username and i want them both send with the socket.

 client.userid = userid;
 client.username = username;
 client.emit('onconnected', { id: client.userid, name: client.username });

i tried this for example but it doesn't seem to work

like image 717
Julien Avatar asked Dec 17 '13 11:12

Julien


People also ask

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.

How many concurrent connections can Socket.IO handle?

Once you reboot your machine, you will now be able to happily go to 55k concurrent connections (per incoming IP).

Is Socket.IO full duplex?

info. WebSocket is a communication protocol which provides a full-duplex and low-latency channel between the server and the browser.

What is emit and on in Socket?

emit('clientEvent', 'Sent an event from the client!' ); </script> <body>Hello world</body> </html> To handle these events, use the on function on the socket object on your server. var app = require('express')(); var http = require('http').


2 Answers

You can try this

io.sockets.on('connection', function (socket) {
  socket.on('event_name', function(data) {
      // you can try one of these three options

      // this is used to send to all connecting sockets
      io.sockets.emit('eventToClient', { id: userid, name: username });
      // this is used to send to all connecting sockets except the sending one
      socket.broadcast.emit('eventToClient',{ id: userid, name: username });
      // this is used to the sending one
      socket.emit('eventToClient',{ id: userid, name: username });
  }
}

and on the client

 socket.on('eventToClient',function(data) {
    // do something with data
       var id = data.id
       var name = data.name // here, it should be data.name instead of data.username

 });
like image 180
Tareq Salah Avatar answered Oct 06 '22 20:10

Tareq Salah


Try sending the object as a whole:

$('form').submit(function(){      
var loginDetails={  
    userid : userid,  
    username : username  
    };  
client.emit('sentMsg',loginDetails);  
}
like image 28
SuriyaPrashath Avatar answered Oct 06 '22 22:10

SuriyaPrashath