UDP Communication


Receiving UDP Data

To receive data from network via UDP, pid_recvfrom function is required. There are two receive buffers of UDP and the following shows how they works. 
※ Refer to Appendix for information about UDP receive buffer size depending on the types of products.

receiving UDP data from network

udp communication 01

reading UDP data from receive buffer

After reading data from receive buffer by calling pid_recvfrom function, PHPoC flushes the buffer.

udp communication 02

reading data size less than received data size

Remaining data after reading will be lost by flushing receive buffer.

udp communication 03

losing data by no available receive buffer

While each of two receive buffers has data which have unread data, subsequent data from network cannot be received. Therefore, it is recommended to read data as soon as possible in received buffer right after checking received data size.

udp communication 04

example

This example prints received UDP data, checking if there is data comes from network every second.

<?php
$rbuf = "";
$pid = pid_open("/mmap/udp0");              // open UDP 0
pid_bind($pid, "", 1470);                   // binding
while(1)                                    // infinite loop
{
    $rxlen = pid_ioctl($pid, "get rxlen");  // get received data size
    if($rxlen)
    {
        pid_recvfrom($pid, $rbuf, $rxlen);  // receive data
        echo "$rbuf\r\n";                   // print received data
    }
    usleep(100000);
}
?>

Sending UDP Data

To send UDP data, pid_sendto function is required.

example of sending UDP data

<?php
$sdata = "01234567";
$pid = pid_open("/mmap/udp0");                             // open UDP 0
$slen = pid_sendto($pid, $sdata, 8, 0, "10.1.0.2", 1470);  // send data
echo "slen = $slen\r\n";                                   // print size of send data
pid_close($pid);
?>