25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Streams and Network Programming ” 249<br />

cols—when you need to take matters into your own hands. Luckily, the stream layer<br />

makes even this much easier to handle than, say, if you were using C. In fact, you can<br />

create socket servers and clients using the stream functions stream_socket_server()<br />

and stream_socket_client(), and then use the traditional file functions to exchange<br />

information:<br />

$socket = stream_socket_server("tcp://0.0.0.0:1037");<br />

while ($conn = stream_socket_accept($socket)) {<br />

fwrite($conn, "Hello World\n");<br />

fclose($conn);<br />

}<br />

fclose($socket);<br />

We can then connect to this simple “Hello World” server using<br />

stream_socket_client().<br />

$socket = stream_socket_client(’tcp://0.0.0.0:1037’);<br />

while (!feof($socket)) {<br />

echo fread($socket, 100);<br />

}<br />

fclose($socket);<br />

Finally, we can run our server just like any other <strong>PHP</strong> script:<br />

$ php ./server.php &<br />

and our client:<br />

$ php ./client.php<br />

Hello World<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

Stream Filters<br />

Stream filters allow you to pass data in and out of a stream through a series of filters<br />

that can alter it dynamically, for example changing it to uppercase, passing it<br />

through a ROT-13 encoder, or compressing it using bzip2. Filters on a given stream

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!