UDP with PHP send and receive sample messages


With PHP you can send very simple packets over UDP on your own computer. To test this, do you need a transmitter and a receiver. Communicate both via the local IP on port in the Biepsiel 20010. The samples must be run on the console.

Transmitter:

<?php
$address = '127.0.0.1';
$port = 20010;
$beat_period = 1;

$fp = stream_socket_client("udp://$address:$port", $errno, $errstr);
if (!$fp) {
 die("ERROR: $errno - $errstr");
}

while (true) {
 $message = sprintf(
 '%s send: %s'. PHP_EOL,
 date('c'),
 rand(0, 1000000)
 );
 fwrite($fp, $message);
 echo $message;

 sleep($beat_period);
}

Receiver:

<?php

$address = '127.0.0.1';
$port = 20010;

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, $address, $port);

if ($socket === false) {
 throw new \RuntimeException(
 sprintf(
 'could not connect to socket address %s on port %s. Error: %s %s',
 $address,
 $port,
 socket_last_error(),
 socket_strerror(socket_last_error())
 )
 );
}

while (true){
 echo socket_read ($socket, 1024);
}

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>