如果您考虑TCP或UDP数据包标头中提供的内容,则不会包含太多身份信息,只包括IP地址。如果您想知道客户的身份,您需要让他们发送某种独特的标识符(例如@madara评论的用户名和密码)。如果它们来自相同的IP,这意味着它们使用相同的路由器,在这种情况下,其目的是掩盖路由器后面的设备。
要检测谁断开连接,首先需要确定谁连接。每个连接都有自己的套接字,即使它们来自同一个IP地址。在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]);
}
}