PHP脚本可以检测套接字是否已关闭?

时间:2009-09-17 01:46:25

标签: php sockets scripting connection webserver

如果远程方的套接字是closed,PHP脚本如何检测?

3 个答案:

答案 0 :(得分:4)

来自socket_read()

socket_read() returns the data as a string on success, or FALSE on error 
(including if the remote host has closed the connection). The error code can 
be retrieved with socket_last_error(). This code may be passed to 
socket_strerror() to get a textual representation of the error.

这是检测套接字是否在大多数语言中关闭的相当标准的方法。我不相信PHP会提供直接的事件样式通知(除了PEAR中的某些内容)。

答案 1 :(得分:0)

fread($socket)立即返回空字符串,而不等待套接字超时。

(不,这不是一个真正的答案,但这是我在我的代码ATM中实施的hackish解决方案。这种行为也可能是特定于Windows的。)

答案 2 :(得分:0)

这不是问题的直接答案,但也许是有价值的笔记。 如果您在多个地方调用socket_close($socket);,并且想查看是否已经关闭插座,可以通过以下比较来完成:

    if (get_resource_type($socket) === 'Unknown') {
        exit;
    }

我通过在关闭var_dump($socket);之前和之后转储套接字来找到它

  • 关闭resource(5) of type (Socket)之前
  • 关闭resource(5) of type (Unknown)
  • 之后

但是它不会告诉您插座是否被另一侧关闭。基本上,建立连接后,总会有两个插座-每侧一个。因此get_resource_type仅会检查您自己的资源,而不会检查另一端。

相关问题