'How to handle socket broken pipe [error 32] in php?
I have socket handler class, which is used to communicate to client with specific ip and port with the help of several socket functions. At the very first time when I am using writetosocket() function, it's working perfectly.
But when I am restarting client(with ip and port). And tries to use writetosocket() it returns me broken pipe error with error code 32. but after some successful execution of socket_write function. Means I am getting this error after some time duration, when I am writing data on socket. I read some solutions and tried most common solution where I am using socket_shutdown and socket_close to terminate socket connection properly whenever I am finding client is not responding. And after that I am again calling startconnection, which is giving me new socket. But still I am getting broken pipe error.
function startconnection(){
/* Create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->socket === false) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
echo "$errorcode : $errormsg";
return false;
}
else {
echo "Socket successfully created.";
}
/* Accept incoming connections */
$this->result = socket_connect($this->socket, $this->ipaddress, $this->port);
if($this->result === false){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
echo "$errorcode : $errormsg";
return false;
}
else {
echo "successfully connected to $this->ipaddress, $this->port";
}
return true;
}
function writetosocket($input){
$sent = socket_write($this->socket, $input, strlen($input));
if($sent === false) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
echo "$errorcode : $errormsg";
return false;
}
else {
echo "Message Sent : $input";
}
return true;
}
Help me to understand and resolve this problem so that function can handle broken pipe error.
Solution 1:[1]
You are getting that error because the server socket has closed and is no longer listening and the client socket is attempting to send data to the server socket after it has been closed but before the port is free to be used again (while it is in TIME_WAIT).
The Server Socket and the Client Socket both go through different steps before they become available for I/O:
SERVER
- socket()
- bind()
- listen()
- accept()
Client
- socket()
- bind() [optional, see below]
- connect() [does an implicit bind on an ephemeral port if not already bound]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
