zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    数据量过大时数据库操作的处理
    VC中回调函数的用法
    基于BindingSource的WinForm开发
    VC获取各类指针
    GetSystemMetrics()函数的用法
    samba建立个人专享网盘
    Windows 7下用Windows照片查看器打开图片速度变慢的解决方案
    这是一个模板
    QT中编译和使用OPENCV
    MFC日志(2011.4.9)
  • 原文地址:https://www.cnblogs.com/liuswi/p/4024563.html
Copyright © 2011-2022 走看看