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/

  • 相关阅读:
    asp网站中使用百度ueditor教程
    URL特殊字符需转义
    织梦DEDE文章列表前面自动加递增数字标签
    dede修改templets模板文件夹后,出现“无法在这个位置找到: ”错误的解决办法
    Mysql命令大全
    成功,来自有梦想,肯坚持
    飞天侠模板的相关修改教程
    bios自检时间长,显示0075错误
    电脑桌面假死解决方法
    没有哪个人是随随便便成功的
  • 原文地址:https://www.cnblogs.com/liuswi/p/4024563.html
Copyright © 2011-2022 走看看