• 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/

  • 相关阅读:
    SHUOJ 1858 分裂的寄生兽
    POJ3057 Evacuation 解题报告
    POJ1149 PIGS 解题报告
    android与javaee通信:登录界面超级简化版
    如何实现服务器与mysql的远程通信?
    关于安卓和服务器通信的一点注意事项
    android中SQLite的基本操作
    jude的一些基本用法
    小项目难点分析
    小项目设想
  • 原文地址:https://www.cnblogs.com/liuswi/p/4024563.html
Copyright © 2020-2023  润新知