php socket_accept陷入僵局

时间:2011-09-12 16:06:26

标签: php sockets

你好我做了一个php套接字服务器从plc获取数据,plc配置为tcp套接字客户端。 我有一个严重的问题,如果本地网络出现故障似乎函数socket_accept停滞不前,plc无法向我发送数据。 如果我重启我的服务器plc正确重新连接。

有人可以帮帮我吗? 我的服务器代码:

error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = ipserver;
$port = 10001;    

if (($sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname("TCP"))) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    exit;
}

if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($sock));
    exit;
} 

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    exit;
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    exit;
}

     while(true)
{
    //$remote_fd = socket_accept($sock);
    if (($remote_fd = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break ;
    }
    do {
        $recv = "";
        if (false === ($recv = socket_read($remote_fd, 128, PHP_BINARY_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($remote_fd)) . "\n";
            #break 2;
        }
        if($recv != "") {
            echo $recv."\n";
            inserisci_letture("t_letture",trim($recv));
            if($sent=socket_write($remote_fd,"1",1)===false)
            {
                echo "socket_write() failed: reason: " . socket_strerror(socket_last_error($remote_fd)) . "\n";
            }
        }
    } 
    while($recv != ""); 
}
socket_shutdown($sock);
socket_close($sock);


?>

1 个答案:

答案 0 :(得分:0)

监听0.0.0.0而不是特定接口,以便在网络(接口)关闭时不关闭套接字。这是一个侦听所有接口的特殊地址。