如何识别客户端 PHP 套接字



所以我给自己准备了一个常规的PHP套接字(或多或少与php手册示例中的代码相同)。我已经找到了一种方法来检测客户端何时断开连接(正常或不正常),但是我如何识别它是谁?IP 地址已停止使用,因为可能有多个用户具有相同的 IP。

提前谢谢。

如果您考虑 TCP 或 UDP 数据包标头中传递的内容,则不包含太多身份信息,仅包含 IP 地址。如果你想知道客户的身份,你需要让他们发送某种唯一标识符(例如@madara注释的用户名和密码)。如果它们来自同一IP,则意味着它们使用相同的路由器,在这种情况下,其目的是掩盖路由器后面的设备。

要检测谁断开了连接,首先需要确定谁连接了。每个连接都有自己的套接字,即使它们来自同一个 IP 地址。在伪 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]);
    }
}

从逻辑上讲,在您的情况下,这很难!这只是一个想法:

如果是聊天,如何将所有在线用户存储在具有以下列的数据库或平面文件中:

NICKNAME
IP
TIME

创建一个函数来检查这些并相应地更新时间,比如每 10 秒更新一次。在此基础上,您将能够确定何时以及谁在线/离线。

------更新------

检查您的套接字错误?使用 get_last_error() 检查错误代码。

$errorcode = socket_last_error(); 
$errormsg=socket_strerror($errorcode); 
die("Error: (".$errorcode.") ".$errormsg."n");

取消设置用户:

if($data === FALSE) {
    socket_close($clients[$i]['socket']);
    unset($clients[$i]);
    echo 'Client disconnected!',"rn";
    continue;
}

从数据库中取消设置客户端。您还可以通过 ID 从$clients数组中识别确切的昵称。

最新更新