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?
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With