Make stream_socket_server workable after receiving the first data packet

I am trying to make a tcp socket server to create and maintain persistent bidirectional messages via PHP stream_socket_server()

.

Short version of the question:

how to create a tcp server using stream_socket_server()

stay alive - don't get data after the first successful reception data, which in my case is one single character entered into the terminal after the telnet command?

Long version - what exactly am I expecting to achieve

- smtp. telnet somehost 25

() smtp-. . hello, . , , . , .

:

<?php

$server = stream_socket_server("tcp://0.0.0.0:4444", $errno, $errorMessage);

if ($server === false) throw new UnexpectedValueException("Could not bind to socket: $errorMessage");

for (;;)  {
    $client = stream_socket_accept($server);

    if ($client) 
    {
        echo 'Connection accepted from ' . stream_socket_get_name($client, false) . "\n";
        echo "Received Out-Of-Band: " . fread($client, 1500) . "\n";
        #fclose($client);
    } 

}

      

, ( ) PHP script i.e. stream_socket_client()

.

The server generated by this script does not support the connection type I described. After executing, telnet localhost 4444

I switched to terminal mode to write a message. When I do this, on the server side, I got the first typed character, and nothing else . No matter what I tried, I could not catch new packets sent from the client side by typing. Likewise, stream_socket_accept()

blocks or ignores everything after receiving the first character data packet. So what am I doing wrong - how do I fix this problem?

+3


source to share


1 answer


Your program only does one read before it starts to accept another incoming connection.

The documentation for fread states that it will return as soon as the package is received. That is, it will not wait for the full 1500 bytes.

Given the slow typing speed, you end up sending a single character packet to your server that comes back and then it accepts to accept another incoming connection.



Place a loop around your reading as such:

for (;;)  {
    $client = stream_socket_accept($server);

    if ($client) {
        echo 'Connection accepted from ' . stream_socket_get_name($client, false) . "\n";
        for (;;) {
            $data = fread($client, 1500);
            if ($data == '') break;
            echo "Received Out-Of-Band: " . $data . "\n";
        }
        fclose($client);
    } 
}

      

+1


source







All Articles