Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom client events in node.js + socket.io

I'm just starting out with node.js, and from what I can tell so far, the way clients communicate with the server is through:

//Client Code 1
var iosocket = io.connect();
iosocket.on('connect', function () {
   iosocket.send("Here's some info");
});

The server becomes aware of this when the 'message' event is recieved:

//Server Code 1
var socketio = require('socket.io');
var io = socketio.listen(server);
io.sockets.on('connection', function (client) {    
    client.on('message', function(msg) {
        //msg== "Here's some info"
    }
});

Now I want the client to be able to provide several distinct events such as:

//Server Code 2
client.on('buttonClicked', function() { ...
client.on('nameChanged', function(newName) { ...

But I'm having trouble figuring out how. The only solution I can come up with using the pieces I have is to send back messages, but have them contain key-value pairs of information:

//Server Code 3
client.on('message', function(msg) {
   kvp = message.split(',');
   if( kvp[0] == 'buttonClicked' )
      ...
   else if( kvp[0] == 'nameChanged' )
      ...
}

But I'm certain there's a proper way of doing this that I just haven't seen in any examples yet. I expect that there's something similar to how the server can generate any event it wants using:

//Server Code 4
io.sockets.emit('serverCustomEvent', eventData);

Which are in turn monitored by the client using:

//Client Code 4
iosocket.on('serverCustomEvent', function(data) {
    //process data
});

Can someone point me in the right direction?

like image 428
Alain Avatar asked Dec 05 '12 21:12

Alain


People also ask

How do you emit a Socket event?

To emit an event from your client, use the emit function on the socket object. To handle these events, use the on function on the socket object on your server.

How do I send to a specific socket IO client?

You can try the code below:io.to(socket.id). emit("event", data); whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.


1 Answers

You can use emit on the client to send custom messages to the server.

iosocket.emit('serverCustomEvent', data);

and on the server

io.sockets.on('connection', function(socket) {
    socket.on('serverCustomEvent', login);
});
like image 97
Musa Avatar answered Oct 26 '22 22:10

Musa