2014-10-28 446 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

相關問題