我正在使用PHP套接字在端口6000上侦听传入连接,并且其工作完美率为99%,但发送请求时发生连接错误的时间为1%服务器。我创建了一个不同的脚本,以无限循环的方式每秒钟在端口6000上ping套接字,并将结果写入日志文件,以便查看它是否中断,以及78,000个成功ping,23失败。PHP Socket随机断开连接
我的代码一定会有一些小的逻辑错误导致这种情况。如果有人有任何想法,非常感谢。
插座:
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if(!socket_bind($sock, "0.0.0.0" , 6000))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
//start loop to listen for incoming connections
while (true)
{
//Accept incoming connection - This is a blocking call
$client = socket_accept($sock);
//read data from the incoming socket
$input = "";
$input = socket_read($client, 10000000);
if ($input != "")
{
// do my logic here with $input
}
}
socket_close($sock);
编辑:不,我没有使用CMD ping通。这是我的PHP脚本这是做ping操作:
<?php
$host = '0.0.0.0';
$port = 6000;
$waitTimeoutInSeconds = 1;
while(true)
{
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds))
{
$file = 'log.txt';
$current = file_get_contents($file);
$today = date("Y-m-d_H:i:s");
$current .= $today . " - SUCCESS\n";
file_put_contents($file, $current);
}
else
{
$file = 'log.txt';
$current = file_get_contents($file);
$today = date("Y-m-d_H:i:s");
$current .= $today . " - FAILED\n";
file_put_contents($file, $current);
}
fclose($fp);
sleep(1);
}
?>
对于实际交易中,客户端只连接一秒钟,而它会通过在原始文本的XML请求,然后做一些逻辑这需要不到一秒钟。既然它在Ping测试中失败了,那意味着我的听众因为某种原因打破了一秒钟呢?
我更新了我的问题与我的脚本ping。是的,这是我的问题。我需要套接字来接受100%的请求。为什么只有少数人会无法工作是没有道理的。 – Jonny07 2013-04-09 15:46:47
放弃之前,您的海绵等待1秒钟。这也可能表明0.03%需要超过1秒才能连接。尝试记录$ errStr和$ errCode。是超时还是别的? – 2013-04-09 15:58:10
啊好点。我已经更新了它,给它5秒的超时时间并回应错误。我会看看是否有更多的错误,并保持发布。 – Jonny07 2013-04-09 16:29:19