TCP Communication


Receiving TCP Data

Data received from network via TCP is stored in receive buffer. pid_recv function is required to read the data.

tcp communication 01

The following shows how to use pid_recv function.

pid_recv($pid, $value[, $len]);

example

This example checks and prints the received TCP data every second.

<?php
$rdata = "";
$pid = pid_open("/mmap/tcp0");              // open TCP 0
pid_bind($pid, "", 0);                      // binding
pid_connect($pid, "10.1.0.2", 1470);        // TCP active connection
do
{
    sleep(1);
    $state = pid_ioctl($pid, "get state");  // get TCP session state
    $rxlen = pid_ioctl($pid, "get rxlen");  // get received data size
    $rlen = pid_recv($pid, $rdata, $rxlen); // receive data
    echo "rlen = $rlen / ";                 // print received data size
    echo "rdata = $rdata\r\n";              // print received data
    if($rlen)
        $rdata = "";                        // flush receive buffer
}
while($state == TCP_CONNECTED);
pid_close($pid);
?>

Sending TCP Data

Data sent by pid_send function is stored in send buffer and transferred to the network via TCP.

tcp communication 01

The following shows how to use pid_send function.

pid_send($pid, $value[, $len]);

example

This example sends data to network via TCP, checking the available space of send buffer every second.

<?php
$sdata = "0123456789";
$pid = pid_open("/mmap/tcp0");                  // open TCP 0
pid_bind($pid, "", 0);                          // binding
pid_connect($pid, "10.1.0.2", 1470);            // TCP active connection
do
{
    sleep(1);
    $state = pid_ioctl($pid, "get state");      // get session state
    // get available space of send buffer
    $txfree = pid_ioctl($pid, "get txfree");    
    $tx_len = pid_send($pid, $sdata, $txfree);  // send data
    echo "tx len = $tx_len\r\n";                // print size of send data
}
while($state == TCP_CONNECTED);
pid_close($pid);
?>

The third argument of pid_send function means the length of sending data. The length of sending data should be less than the remaining data size of send buffer to avoid data loss. It is highly recommended to check the remaining size of send buffer before sending data.