gpt4 book ai didi

php - 我如何检测 PHP 中的流客户端何时不再可用(例如拔掉网线)

转载 作者:可可西里 更新时间:2023-11-01 02:34:45 27 4
gpt4 key购买 nike

是否有任何方法(除了检查 ping 响应)来检测客户端流(我不知道流是否与套接字有任何不同)何时变得不可用(即不再有任何连接但没有干净已断开连接)?

使用这段代码:

#!/usr/bin/env php
<?php
$socket = stream_socket_server(
'tcp://192.168.1.1:47700',
$errno,
$errstr,
STREAM_SERVER_BIND|STREAM_SERVER_LISTEN,
stream_context_create(
array(),
array()
)
);
if (!$socket) {
echo 'Could not listen on socket'."\n";
}
else {
$clients = array((int)$socket => $socket);
$last = time();
while(true) {
$read = $clients;
$write = null;
$ex = null;
stream_select(
$read,
$write,
$ex,
5
);
foreach ($read as $sock) {
if ($sock === $socket) {
echo 'Incoming on master...'."\n";
$client = stream_socket_accept(
$socket,
5
);
if ($client) {
stream_set_timeout($client, 1);
$clients[(int)$client] = $client;
}
}
else {
echo 'Incoming on client '.((int)$sock)."...\n";
$length = 1400;
$remaining = $length;

$buffer = '';
$metadata['unread_bytes'] = 0;
do {
if (feof($sock)) {
break;
}

$result = fread($sock, $length);

if ($result === false) {
break;
}

$buffer .= $result;

if (feof($sock)) {
break;
}

$continue = false;

if (strlen($result) == $length) {
$continue = true;
}

$metadata = stream_get_meta_data($sock);
if ($metadata && isset($metadata['unread_bytes']) && $metadata['unread_bytes']) {
$continue = true;
$length = $metadata['unread_bytes'];
}
} while ($continue);

if (strlen($buffer) === 0 || $buffer === false) {
echo 'Client disconnected...'."\n";
stream_socket_shutdown($sock, STREAM_SHUT_RDWR);
unset($clients[(int)$sock]);
}
else {
echo 'Received: '.$buffer."\n";
}
echo 'There are '.(count($clients) - 1).' clients'."\n";
}

}
if ($last < (time() - 5)) {
foreach ($clients as $id => $client) {
if ($client !== $socket) {
$text = 'Yippee!';
$ret = fwrite($client, $text);
if ($ret !== strlen($text)) {
echo 'There seemed to be an error sending to the client'."\n";
}
}
}
}
}
}
if ($socket) {
stream_socket_shutdown($socket, STREAM_SHUT_RDWR);
}

和另一台计算机上的套接字客户端,我可以连接到服务器,发送和接收数据,然后完全断开连接,一切都按预期运行。但是,如果我在客户端计算机上建立网络连接,则在服务器端没有检测到任何东西 - 服务器会继续监听客户端套接字,并且还会写入它而不会出现任何错误。

最佳答案

据我所知,调用 feof($stream) 会告诉您远程套接字是否已断开连接,但我对此不是绝对确定。在继续研究解决方案的同时,我自己也在使用 ping/pong。

关于php - 我如何检测 PHP 中的流客户端何时不再可用(例如拔掉网线),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16715313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com