2014-10-28 448 views
1

我使用socket_create()创建套接字资源,然后我绑定IP地址由它socket_bind(),其工作正常;PHP警告:socket_read():无法读取套接字[104]:连接重置对等

但线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); 

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

回答

0

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

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

+0

我编辑我的问题。 – 2014-10-28 16:22:57

+0

socket_last_error()在socket_create()后不显示任何错误。 – 2014-10-28 16:40:40

+0

但是,在执行在给定时间导致警告的表达式之前它会显示错误吗?你应该在发出'socket_read'之前测试你的套接字。如果由'socket_last_error'报告的错误重新创建您的SMTP会话。再次执行整个socket_create部分。 – itsafire 2014-10-28 18:34:58

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); 
} 
+0

我添加了一些看起来像你的代码,但套接字连接成功,并通过检查是否语句,然后在socket_read线上抛出错误。 – 2014-10-28 16:38:44

+0

我更新了代码,以便它检查socket_read是否返回了任何数据。 – dnshio 2014-10-28 16:44:55

+1

我把socket_connect放在'if'语句中,但是socket_connect返回true,但是socket_read抛出这个错误。 :( – 2014-10-30 19:11:00

相关问题