Alain
Alain

Reputation: 27250

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?

Upvotes: 6

Views: 7042

Answers (1)

Musa
Musa

Reputation: 97717

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);
});

Upvotes: 11

Related Questions