Can't read from socket (hangs)

前端 未结 4 1602
深忆病人
深忆病人 2021-02-06 07:17

I am using PHP to connect to a local C++ socket server to keep state between a web app and a couple of daemons. I can send data to the socket server, but not receive from it; i

4条回答
  •  执笔经年
    2021-02-06 07:57

    Sockets in PHP, as in most programming languages, are opened in blocking mode by default, unless set otherwise using socket_set_nonblock.

    This means that unless a timeout/error occurs or data is received, socket_read will hang there forever.

    Since your termination character seems to be a new line, try that:

    while($resp = socket_read($sock, 1000)) {
       $str .= $resp;
       if (strpos($str, "\n") !== false) break;
    }
    socket_close($sock);
    die("Server said: $str");
    

提交回复
热议问题