Creating s simple client/server UDP example in PHP

11,613

Here is the warning on the very same page

Warning
This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

Share:
11,613
Litre
Author by

Litre

Updated on June 05, 2022

Comments

  • Litre
    Litre almost 2 years

    I'm trying to make a simple UDP client server example in PHP but I face an error.

    This is the client :

    $fp = stream_socket_client("udp://192.168.0.12:12478", $errno, $errstr);
    
    if ($fp)
    {
            fwrite($fp, "TEST 1 TEST 2 TEST 3");
            $buf = fgets($fp);
            var_dump($buf);
            fclose($fp);
    }
    

    This is the server :

    $socket = stream_socket_server("udp://192.168.0.12:12478", $errno, $errstr, STREAM_SERVER_BIND);
    if ($socket)
    {
      while ($conn = stream_socket_accept($socket)) {
        fwrite($conn, date("D M j H:i:s Y\r\n"));
        fclose($conn);
      }
      fclose($socket);
    }
    

    All executions end with :

    Warning: stream_socket_accept(): accept failed: Operation not supported 
    

    Basically, this is the example given in all PHP documentations but I can't figure what is wrong in it. Any help is greatly appreciated.

    Thanks.