14.6 UNIX Domain Sockets


You want to connect to a UNIX domain socket because you are communicating to processes only on the local machine.

Technique

For servers:

 <?php $sock = socket(AF_UNIX, SOCK_STREAM, 0); if ($sock < 0)     die(strerror($sock)); unlink("/tmp/sterlingsock"); if (($ret = bind($sock, "/tmp/sterlingsock")) < 0)     die(strerror($ret)); if (($ret = listen($sock, 5)) < 0)     die(strerror($ret)); while (($csock = accept_connect($sock)) < 0) {     // .. Manipulate client socket, $csock here } close($sock); ?> 

For clients :

 <?php $sock = socket(AF_UNIX, SOCK_STREAM, 0); if ($sock < 0)     die(strerror($sock)); if (($ret = connect($sock, "/tmp/sterlingsock")) < 0)     die(strerror($ret)); if (($ret = write($sock, $data, $data_len)) < 0)     die(strerror($ret)); while (($ret = read($sock, $buf, $buflen)) < 0) {     print $buf; } close($sock); ?> 

Comments

Most UNIX domain sockets have names for the filesystem, just like any ordinary file. In fact, they are considered to be a type of file, so you can perform stat operations on them.

In the preceding example, we use the stream method of connecting to the local socket, but we could have just as easily used the datagram (udp) method:

For servers:

 <?php $sock = socket(AF_UNIX, SOCK_DGRAM, 0); if ($sock < 0)     die(strerror($sock)); unlink("/tmp/sterlingsock"); if (($ret = bind($sock, "/tmp/sterlingsock")) < 0)     die(strerror($ret)); while (recvfrom($sock, $buf, $buflen, $addr, $port) > 0) {     // .. manipulate $addr & $port here. } ?> 

For clients:

 <?php $addr = '127.0.0.1'; $port = 67; $sock = socket(AF_UNIX, SOCK_DGRAM, 0); if ($sock < 0)     die(strerror($sock)); sendto($sock, $data, $datalen, $addr, $port); if (($ret = recv($sock, $buf, $buflen, $newaddr, $newport)) < 0)     die(strerror($ret)); ?> 


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