I use socket_create()
to create socket Resource,then I bind an IP
address to it by socket_bind()
, its works fine;
But after a while(more than 30 minutes) in line socket_read($sock, 2048)
this error thrown :
"PHP Warning: socket_read(): unable to read from socket [104]: Connection reset by peer in test.php on line 198"
.
This is my simplified code:
$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);
This piece of code make a SMTP(port 25) connection to a MX Host at the other side. Maybe it's the fault on the other side of your connection, But how can I detect that the other side isn't ready for the connection right now. In the other word how can I find out the "Connection reset by peer" occurred?
You should check if socket_connect()
was successful before reading from it.
so you could rewrite your code like this:
-- UPDATED --
$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);
}