doudang4568 2017-08-01 15:25
浏览 109

PHP Socket客户端:测试服务器连接

I have socket client which connects to server and which wait for datas to be sent by this server. It works fine but, when server has a disconnection, it has to be detected by socket client in order to try a reconnection.

Client socket code :

$co = false;
while (!$co) {

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        echo "socket_create()error :  " . socket_strerror(socket_last_error()) . "
";
    } else {
        echo "OK 1.
";
    }

    echo "Try connection '$address' on port '$service_port'... 
";
    $result = socket_connect($socket, $address, $service_port);
    if ($socket === false) {
        echo "socket_connect() error : ($result) " . socket_strerror(socket_last_error($socket)) . "
";
    } else {
        socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
        echo "OK 2.
";
        $co = true;
    }
}

while (true) {
    echo 'read' . PHP_EOL;
    socket_clear_error($socket);
    $out = socket_read($socket, 2048);
    $socket_last_error = socket_last_error($socket);
    $strErr = socket_strerror($socket_last_error) . ' ' . $socket_last_error;
    echo("socket_last_error : " . $strErr);
    var_dump($out);
} 

Problem is when client socket is correctly connected to server, there's socket_last_error with value 'Resource temporarily unavailable 11' and 'socket_read' function return false when server doesn't send data.

But when server is deconnected, there's socket_last_error with value 'Success 0' and 'read' function return ''

PHP doc says :

socket_read() returns data as string on success, or FALSE on error (including case where remote host has closed connection).

So functions results are unexpected and I would like to know what's the right method to detect a server disconnection in order to try a new connection?

Thanks in advance for your answers.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
    • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
    • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
    • ¥20 腾讯企业邮箱邮件可以恢复么
    • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
    • ¥15 错误 LNK2001 无法解析的外部符号
    • ¥50 安装pyaudiokits失败
    • ¥15 计组这些题应该咋做呀
    • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
    • ¥15 让node服务器有自动加载文件的功能