8

最近,我们需要检测客户端何时从服务器突然中止/断开连接。突然,我的意思是不一定通过浏览器的STOP按钮,实际上,客户端是通过 POST 发送的 SOAP 消息(使用soapUI),因此,断开连接可能就像在收到之前停止( Ctrl + C )客户端一样简单一个答复。我们花了几天时间试图找到一个解决方案,直到我们找到了解决办法。因此,这可能是一个带有隐含响应的问题,但目标是提供可以帮助许多其他有相同需求的人的信息。

以下是我们使用服务器检测客户端断开连接的基本代码:

<?PHP
ignore_user_abort(true);            // Continue running the script even when the client aborts/disconnects

sleep(5);                           // Sleep 5 seconds so we can stop the client before it recieves a reponse from the server

echo "RESPONSE sent to the client"; // Response to the Request
ob_flush();                         // Clean output buffer
flush();                            // Clean PHP's output buffer
usleep(500000);                     // Sleep half a second in order to detect if Apache's server sent the Response
echo " ";                           // Echo a blank space to see if it could be sent to the client
ob_flush();                         // Clean output buffer
flush();                            // Clean PHP's output buffer

if(connection_status() != 0) {      // Client aborted/disconnected abruptly
  return -1;
}
else {                              // Client recieved the response correctly
  return 0;
}

?>
4

1 回答 1

2

PHP 中的“ connection_aborted ”函数将解决您的问题。

您可以在此链接中查看带有示例用法的函数语法。

于 2012-12-23T17:39:03.880 回答