PHP警告:socket_read():无法从套接字[104]读取:由对等方重置连接

时间:2014-10-28 16:08:00

标签: php sockets telnet php-5.4

我使用socket_create()来创建套接字资源,然后我通过IPsocket_bind()地址绑定到它,它的工作正常;

但是在socket_read($sock, 2048)行中一段时间​​(超过30分钟)后抛出了这个错误:

"PHP Warning: socket_read(): unable to read from socket [104]: Connection reset by peer in test.php on line 198"

这是我的简化代码:

$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// check if tcp socket ceated or not
if ($this->sock === false) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
     die("Couldn't create socket: [$errorcode] $errormsg");
}

// Bind the source address
socket_bind($this->sock, $this->ip);
// Connect to destination address
socket_connect($this->sock, $this->mxHost, $this->port);
$buf = socket_read($this->sock, 2048);

这段代码与另一侧的MX主机建立SMTP(端口25)连接。 也许这是你连接另一端的错误,但我怎么能检测到另一方现在还没有为连接做好准备。换句话说,如何找出“通过对等方重置连接”?

2 个答案:

答案 0 :(得分:1)

在阅读之前,您应该检查socket_connect()是否成功。

所以你可以像这样重写你的代码:

- 更新 -

$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Bind the source address
socket_bind($this->sock, $this->ip);
// Connect to destination address
if (socket_connect($this->sock, $this->mxHost, $this->port)) {
    // suppress the warning for now since we have error checking below
    $buf = @socket_read($this->sock, 2048);

    // socket_read() returns a zero length string ("") when there is no more data to read.
    // This indicates that the socket is closed on the other side. 
    if ($buf === '') 
    { 
        throw new \Exception('Connection reset by peer'); 
    } 
} else {
    // Connection was not successful. Get the last error and throw an exception
    $errorMessage = socket_strerror(socket_last_error());
    throw new \Exception($errorMessage);
}

答案 1 :(得分:0)

嗯......你的同伴重置连接。也许这是你连接另一端的错?超时机制可能正在另一端运行。

您可以在使用socket_last_error函数写入套接字之前测试套接字,并在断开连接时重新创建连接。