php: How to save the client socket (not closed), so a further script may retrieve it to send an answer?

前端 未结 2 389
别跟我提以往
别跟我提以往 2021-01-14 04:48

I have a client-server application, in which the server may require to send information back to clients.

As the client-server pattern does not allow the server to \"

相关标签:
2条回答
  • 2021-01-14 04:59

    One way to solve it - forget about sockets.

    Pseudocode:

    // receive request, set some session_id if not exists
    // request contains last_timestamp, so we know which data client already have
    // check have we any dataset for this session_id after last_timestamp
    // return this dataset, or no_new_data signature
    

    Data can be stored in database, for example.

    0 讨论(0)
  • 2021-01-14 05:04

    So, you need two connections for each client, one persist for get data from server, and other to send data to.

    Something like:

    in persist.php:

    $socket = stream_socket_server('unix:///tmp/unique.sock', $errno, $errstr);
    if (!$socket) {
      echo "$errstr ($errno)<br />\n";
    } else {
      while ($conn = stream_socket_accept($socket)) {
        $buffer = "";
        // Read until double CRLF
        while( !preg_match('/\r?\n\r?\n/', $buffer) )
            $buffer .= fread($client, 2046); 
    
        //Operate with our listener
        echo $buffer;
        flush();
    
        // Respond to socket client
        fwrite($conn,  "200 OK HTTP/1.1\r\n\r\n");
        fclose($conn);
      }
      fclose($socket);
    }
    

    in senddata.php:

    $sock = stream_socket_client('unix:///tmp/unique.sock', $errno, $errstr);
    fwrite($sock, $data);
    fflush($sock);
    fclose($sock);
    
    0 讨论(0)
提交回复
热议问题