14.4 A UDP Client


You want to create a UDP client.

Technique

For an easy-to-use, abstracted interface, use the fsockopen() function:

 <?php $fp = fsockopen("udp://127.0.0.1", 13, $errno; $errstr); fwrite($fp, $msg); while ($line = fread($fp, $len)) {     print $line; } fclose($fp); ?> 

Or, you can use the more advanced, low-level functions:

 <?php $addr = gethostbyname('127.0.0.1'); $port = 50; $sock = socket (AF_INET, SOCK_DGRAM, getprotobyname('udp')); if ($sock < 0)     die(strerror($sock)); if (($ret = sendto($sock, $data, $dlen, 0, $addr, $port)) < 0)     die(strerror($sock)); while (recvfrom($sock, $buf, $blen, 0, $addr, $port) > 0)     print $buf; 

Comments

There are two types of sockets you can use with PHP: stream sockets ( SOCK_STREAM ) and datagram sockets ( SOCK_DGRAM ). Stream sockets are more like files; they give the illusion of a stable connection in which data streams from the socket and to the socket. Although streaming sockets are more expensive on your system resources, what they lack in speed, they make up in ease of use and reliability.

Datagram sockets provide no such reliability or ease of use. Datagrams are meant for speed; they offer no assurances that your data will arrive, or that your data will arrive in the proper order.

It might seem odd to use datagram sockets if they are so unreliable. Surely, the speed increase is surely not worth the lack of reliability?

In some applications, such as streaming audio, where it's more important that the whole is preserved than that individual packets get through, datagram sockets make more sense because of their speed. Datagram (udp) sockets are also a widely used method for broadcasting where the data is sent, but it isn't particularly imperative that the target accepts it.



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