PHP Socket Client

This is a simple client that is running two different requests. One at every 2 seconds and another every 5 minutes. The 2 second one retrieved data from server and the 5 minute one sends data to server.

<?php
set_time_limit(0);
ob_implicit_flush();

$host    = "xxx.xxx.xxx.xxx";
$port    = 1250;

$lastUpdate = time();

while(1)
{
    if(time() - $lastUpdate > 300) //if 5 minutes elapsed
    {
        $message = "action=4512|temp=29.67|paM=10025.69|paH=125.69|led1=1|led2=0\r\n"; // the data to be sent separated by | The \r\n is important - it will tell the server that the string/data ends there
        // create socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
        // connect to server
        $result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
        
        // send command/query to server
        socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
        // get server response
        $result = socket_read ($socket, 1024, PHP_NORMAL_READ) or die("Could not read server response\n"); // 1024 is the max bytes that the socket will read if no \r\n is encountered. For the \n\r terminator PHP_NORMAL_READ is needed.
        echo "Reply From Server: ".$result."\n";
        
        // close socket
        socket_close($socket);
        
        $lastUpdate = time();
    }
    else
    {
        $message = "action=1223\r\n";
        // create socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
        // connect to server
        $result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");  
        
        // send command/query to server
        socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
        // get server response
        $result = socket_read ($socket, 1024, PHP_NORMAL_READ) or die("Could not read server response\n");
        echo "Reply From Server: ".$result."\n";
        
            // close socket
        socket_close($socket);
    }
    
    flush(); //may be this can be removed
    sleep(2);
    flush();
}
?>

 

Leave a Reply