skip to Main Content

The following code should return the whole message all the time but it doesn’t… I keep refreshing and at some point it prints:

Connected to UWT-RTR-002

And some others as expected:

Connected to UWT-RTR-002 Wireshark full trace start/stop control program Type "help" for instructions 2024-07-08 12:08:50 command:

Then I tried to pass the command "help" but I get nothing… It works when I use telnet on Windows Command Prompt.

UPDATE: while is taking too long, it doesn’t display any error.

$address = '10.0.0.200';
$port = 41200;
$sock = stream_socket_client("tcp://".$address.":".$port, $errno, $errstr); 
fwrite($sock, "helpn");
while ($data = fread($sock, 8192)){
    echo $data."<br>";
}
fclose($sock);

Trying to read and send commands to a TCP

2

Answers


  1. Chosen as BEST ANSWER

    This is what the server-guy did and it loads fast:

    <?php
    
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);
    
    set_time_limit(0);
    ob_implicit_flush();
    
    $address = '10.0.0.200';
    $port = 41200;
    echo "<b>Address:</b> ".$address." <b>PORT</b> ".$port."n";
    
    
    $socket = stream_socket_client("tcp://".$address.":".$port,$errno, $errstr, 30);
    if (!$socket)
    {
        echo "error opening socket";
        die();
    }
    
    stream_socket_sendto($socket, "helpn");
    
    $command_sent = 0;
    
    while(!feof($socket))
    {
        $data = stream_get_line($socket, 1500, "n");
        echo $data."<br>n";
        if ($data == 'command:')
        {
            if ($command_sent == 0)
            {
                stream_socket_sendto($socket, "statusn");
            }
            else
            {
                stream_socket_sendto($socket, "exitn");
            }
            $command_sent = 1;
        }
    }
    
    fclose($socket);
    echo "donen";
    ?>
    

  2. Since TCP doesn’t have message boundaries, you have to define a way to tell how long the message is yourself. One option is to send the message length first, then read that many bytes in a loop.

    This code will work as long as messages are less than 256 bytes long.

    $address = '10.0.0.200';
    $port = 41200;
    $sock = stream_socket_client("tcp://".$address.":".$port, $errno, $errstr); 
    $msg = "help";
    fwrite($sock, chr(strlen($msg)));
    fwrite($sock, $msg);
    $length = ord(fread($sock, 1));
    $recv_msg = '';
    while ($length > 0 && $data = fread($sock, $length)){
        $recv_msg .= $data;
        $length -= strlen($data);
    }
    echo $recv_msg . "<br>";
    fclose($sock);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search