14.5 A UDP Server


You want to create a UDP server.

Technique

Simply bind the created socket to a port and then you receive data by using the recvfrom() function:

 <?php set_time_limit(0); $addr = "127.0.0.1"; $port = 500; $sock = socket(AF_INET, SOCK_DGRAM, 0); if ($sock < 0)     die(strerror($sock)); if (($ret = bind($sock, $addr, $port)) < 0)     die(strerror($ret)); while (($read = recvfrom($sock, $buf, $buflen, 0, $name, $port)) > 0) {     // .. $name contains your socket. } close($sock); ?> 

Comments

Creating a UDP server is much easier than creating a TCP server because when UDP requests come in, we don't have to create a whole new socket connection. We simply get the data from the user as well as his address, and then we can do what we want to do with that data. Examine the following simple script, which will receive data and then send a message based on that data:

 <?php set_time_limit(0); $addr = "127.0.0.1"; $port = 500; $sock = socket(AF_INET, SOCK_DGRAM, 0); if ($sock < 0)     die(strerror($sock)); if (($ret = bind($sock, $addr, $port)) < 0)     die(strerror($ret)); while (($read = recvfrom($sock, $buf, strlen($buf), 0, $name, $port)) > 0) {     // is_valid_packet() is a custom function which     // validates the packet sent to the server.     if (is_valid_packet ($buf)) {         $resp = "Well it looks like your packet was valid";         $resp .= "Here is the contents of your packet $buf";     } else {         $resp = "Sorry, Invalid packet";     }     sendto($socket, $resp, strlen($resp), 0, $name, $port); } close($sock); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net