如何在php中处理套接字断开的管道[error 32]?
我有一个套接字处理程序类,它通过几个套接字函数与具有特定ip和端口的客户端通信。当我第一次使用如何在php中处理套接字断开的管道[error 32]?,php,sockets,Php,Sockets,我有一个套接字处理程序类,它通过几个套接字函数与具有特定ip和端口的客户端通信。当我第一次使用writetosocket()函数时,它工作得非常好 但当我重新启动客户端时(使用ip和端口)。并尝试使用writetosocket()返回我的断管错误,错误代码为32。但是在成功执行了socket\u write函数之后。这意味着,当我在套接字上写入数据时,经过一段时间后会出现此错误。我阅读了一些解决方案,并尝试了最常见的解决方案,其中我使用socket\u shutdown和socket\u clo
writetosocket()
函数时,它工作得非常好
但当我重新启动客户端时(使用ip和端口)。并尝试使用writetosocket()
返回我的断管错误,错误代码为32。但是在成功执行了socket\u write
函数之后。这意味着,当我在套接字上写入数据时,经过一段时间后会出现此错误。我阅读了一些解决方案,并尝试了最常见的解决方案,其中我使用socket\u shutdown
和socket\u close
在发现客户端没有响应时正确终止套接字连接。在那之后,我再次调用startconnection,它为我提供了新的套接字。但我还是得到了管道断裂的错误
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;
}
请帮助我理解并解决此问题,以便函数能够处理断管错误。您之所以会遇到此错误,是因为服务器套接字已关闭且不再侦听,客户端套接字在关闭后试图向服务器套接字发送数据,但在端口可以自由再次使用之前(当它处于等待时间时)
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;
}
服务器套接字和客户端套接字在可用于I/O之前都经过不同的步骤:
服务器
显示更多代码(例如创建
$this->socket
。@nouney我已经包含了创建socket的代码。请检查。谢谢Charles,但我实际上已成功连接到客户端,我可以借助socket的新资源id进行验证。在客户机上成功地进行了一些套接字写入之后,我在套接字写入时遇到了管道断开的情况。