75
236
”
StreamsandNetworkProgramming
are organized ina chain—thus,you cansetthem up sothat the data passes through
multiple filters, sequentially.
You can add a filter to a stream by using
stream
_
filter
_
prepend()
and
stream
_
filter
_
append()
—which, as you might guess, add a filter to the beginning
and end ofthefilter chainrespectively:
$socket = stream
_
socket
_
server("tcp://0.0.0.0:1037");
while ($conn = stream
_
socket
_
accept($socket)) {
stream
_
filter
_
append($conn, ’string.toupper’);
stream
_
filter
_
append($conn, ’zlib.deflate’);
fwrite($conn, "Hello World\n");
fclose($conn);
}
fclose($socket);
In this example, we apply the
string.toupper
filter to our server stream, which will
convert the data to upper case, followed by the
zlib.deflate
filter to compress it
whenever we write data to it.
We can then apply the
zlib.inflate
filter to the client, and complete the imple-
mentationofa compressed data streambetweenserver and client:
$socket = stream
_
socket
_
client(’tcp://0.0.0.0:1037’);
stream
_
filter
_
append($socket, ’zlib.inflate’);
while (!feof($socket)) {
echo fread($socket, 100);
}
fclose($socket);
If you consider how complex the implementation of a similar compression mech-
anism would have normally been, it’s clear that stream filters are a very powerful
feature.
Summary
As you cansee, streams penetrate to the deepest levels of PHP, from general file ac-
cesstoTCP andUDP sockets. Itis evenpossible tocreate your ownstreamprotocols
and filters, making this the ultimate interface for sending and receiving data with