2013-04-09 112 views
0

我正在使用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测试中失败了,那意味着我的听众因为某种原因打破了一秒钟呢?

回答

0

我不确定我是否理解正确。

你说约有0.03%的ping失败。这是你的问题吗?如果这些是真实ping(来自cmd.exe的ping.exe),那么它与您的逻辑无关。这是网络。 (启用WiFi的主机?)

如果你确信这是你的逻辑: 如果有人连接,多长时间,他有联系吗?连接到前一个客户端的新请求会发生什么?我想你可能会在这里找到你的答案。

也尝试使用连续连接和发送虚拟数据的客户端进行测试,而不是ping。并记录客户端收到的回复。

+0

我更新了我的问题与我的脚本ping。是的,这是我的问题。我需要套接字来接受100%的请求。为什么只有少数人会无法工作是没有道理的。 – Jonny07 2013-04-09 15:46:47

+0

放弃之前,您的海绵等待1秒钟。这也可能表明0.03%需要超过1秒才能连接。尝试记录$ errStr和$ errCode。是超时还是别的? – 2013-04-09 15:58:10

+0

啊好点。我已经更新了它,给它5秒的超时时间并回应错误。我会看看是否有更多的错误,并保持发布。 – Jonny07 2013-04-09 16:29:19