dongzang5815 2012-09-26 19:36
浏览 291
已采纳

如何识别客户端PHP Socket?

So I've got myself a regular PHP socket (More or less the same code from the example from the php manual). I have found a way to detect when a client disconnects (gracefully or not), but how can I identify who it was? IP address use is out because there might be more than one user with the same IP.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • douyi9705 2012-09-26 19:43
    关注

    If you think about what is delivered in a TCP or UDP packet header, there isn't much identity information included, just the IP address. If you want to know the identity of clients you need to have them send some sort of unique identifier (e.g. username & password as @madara commented). If they're from the same IP that means that they're using the same router in which case its purpose is to mask what devices are behind the router.

    To detect who disconnected, you first need to determine who connected. Each connection gets its own socket, even if they're coming from the same IP address. In psuedo php:

    // Store all active sockets in an array
    $online_users = array();
    
    // Open up a listening socket
    $listener = socket_create(...);
    socket_listen($listener);
    $client_sock = socket_accept($listener);
    
    // Have the client send authentication stuff after connecting and
    // we'll receive it on the server side
    $username = socket_read($client_sock, $len);
    // Map the username to the client socket
    $online_users[$username] = $client_sock;
    
    // Continue to read or write data to/from the sockets. When a read or
    // write fails, you just iterate through the array to find out who
    // it was. If the socket $failed_sock failed, do as follows
    foreach ($online_users as $name => $socket)
    {
        if ($socket == $failed_sock)
        {
            // $name is the username of the client that disconnected
            echo $name . ' disconnected';
            // You can then broadcast to your other clients that $name
            // disconnected. You can also do your SQL query to update the
            // db here.
            // Finally remove the entry for the disconnected client
            unset($online_users[$name]);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable