by
obiAdmin (raymond): 30 September 2006
In our
last section, we built the client chat room so
people can go on and message each other. In this section
we will build the PHP5 socket script to handle the
client connections and messages.
Go ahead and copy and paste all of the
following code into a
new PHP file. Save it as socketShell.php.
- #!/usr/bin/php
-q
- <?php
- /*
- Raymond Fain
- Used for PHP5 Sockets with
Flash 8 Tutorial for Kirupa.com
- For any questions or
concerns, email me at [email protected]
- or simply visit the site,
www.php.net, to see if you can find an answer.
- */
-
-
- error_reporting(E_ALL);
-
- set_time_limit(0);
-
- ob_implicit_flush();
-
- $address
=
'192.168.0.16';
- $port
=
9999;
-
- //---- Function to Send
out Messages to Everyone Connected
----------------------------------------
-
- function
send_Message($allclient,
$socket,
$buf)
{
- foreach($allclient
as
$client)
{
- socket_write($client,
"$socket wrote: $buf");
- }
- }
-
-
-
- //---- Start Socket
creation for PHP 5 Socket Server
-------------------------------------
-
- if
(($master
=
socket_create(AF_INET,
SOCK_STREAM,
SOL_TCP))
<
0)
{
- echo
"socket_create() failed,
reason: " .
socket_strerror($master)
. "\n";
- }
-
- socket_set_option($master,
SOL_SOCKET,SO_REUSEADDR,
1);
-
-
- if
(($ret
=
socket_bind($master,
$address,
$port))
<
0)
{
- echo
"socket_bind() failed,
reason: " .
socket_strerror($ret)
. "\n";
- }
-
-
- if
(($ret
=
socket_listen($master,
5))
<
0)
{
- echo
"socket_listen() failed,
reason: " .
socket_strerror($ret)
. "\n";
- }
-
-
-
- $read_sockets
=
array($master);
-
- //---- Create Persistent
Loop to continuously handle incoming socket messages
---------------------
- while
(true)
{
- $changed_sockets
=
$read_sockets;
-
- $num_changed_sockets
=
socket_select($changed_sockets,
$write
=
NULL,
$except
=
NULL,
NULL);
-
- foreach($changed_sockets
as
$socket)
{
-
- if
($socket
==
$master)
{
-
- if
(($client
=
socket_accept($master))
<
0)
{
- echo
"socket_accept()
failed: reason: " .
socket_strerror($msgsock)
. "\n";
- continue;
- }
else
{
- array_push($read_sockets,
$client);
- }
- }
else
{
-
- $bytes
=
socket_recv($socket,
$buffer,
2048,
0);
-
- if
($bytes
==
0)
{
- $index
=
array_search($socket,
$read_sockets);
- unset($read_sockets[$index]);
-
socket_close($socket);
- }else{
- $allclients
=
$read_sockets;
-
array_shift($allclients);
-
send_Message($allclients,
$socket,
$buffer);
- }
- }
-
- }
- }
-
- ?>
As you can see, there is a lot that
makes this stuff work! I hope your not running away
already. Tackling this thing isn't as bad as you think.
In the downloadable zip file I have provided at the end
of this tutorial, I have included all the comments that
you will need to understand this bad boy!!
On the
next page I will briefly go over
some things that you see here.
So onwards to the
next
page!
|