Can't read from socket (hangs)

前端 未结 4 1555
深忆病人
深忆病人 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:49

    TCP sockets usually try to combine multiple small send calls into one packet to avoid sending too many packets (Nagle's algorithm). This may be the cause that you can't receive anything after the send() call. You will have to open the socket with TCP_NODELAY to avoid that.

    0 讨论(0)
  • 2021-02-06 07:56

    You can also try this when reading from socket:

    if(socket_recv ( $socket , $response , 2048 , MSG_PEEK)!==false)
    {
       echo "Server said: $response";
    }
    

    Note: Using MSG_WAITALL in place of MSG_PEEK might cause socket to hang (from one experience I once had).

    0 讨论(0)
  • 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");
    
    0 讨论(0)
  • 2021-02-06 08:00

    I actually just fixed a problem similar to this, except with pipes (Is php's fopen incompatible with the POSIX open for pipes). I don't know to what extent the solution would be similar, but maybe worth a look? I agree with RageD that you should stick a cout between the read and write lines just to test and see if the C++ is hanging on the sock >> data line or the sock << data line...

    0 讨论(0)
提交回复
热议问题