Socket.io 0.7 – Sending messages to individual clients

Note that this is just for Socket.io version 0.7, and possibly higher if they don’t change the API again.

I’m writing an iPhone app right now using PhoneGap and jQuery Mobile on the phone, and node.js and socket.io on an Amazon EC2 server, and I hit a wall when I started using Socket.io. The problem is that the documentation is sparse, disorganized, and hard to find. In addition to that, there are dozens of blog posts and community members who’ll teach you how to do things in older versions of socket, but the API has changed, so you just end up with undefined errors.

My exact problem was with sending messages to individual clients.

// on the server
var users = {};
io.sockets.on('connection', function (socket) {
    socket.emit('who are you');
    socket.on('check in', function (incoming) {
        users[incoming.phonenumber] = socket.id;
    });
});

// on the client
socket.on('who are you', function (incoming) {
    socket.emit('check in', {phonenumber: savedphonenumber});
});

To recap: The server is listening for connections. When a client connects, the server emits the custom message “who are you”. The client hears it and responds with it’s identifier (I’m using their phone number, which I verify and store earlier in the process). The server then stores the client’s socket ID in a users object, with their identifier as the key, and the socket ID as the value.

From then on, it’s a simple case of grabbing the user’s socket ID from the user’s table when you need to send them a message, and sending it like this:

var socketid = users[clientphonenumber];
io.sockets.socket(socketid).emit('for your eyes only');

One thing to consider is what happens to that users object if you have thousands of users. It’ll get pretty bloated, pretty quickly. You need to figure out a strategy for removing users from the users object if they disconnect AND if you don’t hear from them in a while (in case the disconnect event doesn’t fire).

Source:http://chrissilich.com/blog/socket-io-0-7-sending-messages-to-individual-clients/

原文地址:https://www.cnblogs.com/liuswi/p/4024563.html