The following is a simple message processing server that is implemented through the socket Extension Module of PHP: Binding on a local port, listening to the client's connection, receiving data and forwarding to all clients other than the sender
socket_server.php
Copy Code code as follows:
#!/usr/bin/env PHP
<?php
Author:zhxia
if (!extension_loaded (' sockets ')) {
Die (' The sockets extension is not loaded! ');
}
Const port=9981;
$socket =socket_create (af_inet,sock_stream,sol_tcp) or Die (' socket create error! ');
#通过设置这个选项, reuse of ports
Socket_set_option ($socket, sol_socket,so_reuseaddr,1);
Socket_bind ($socket, 0,port);
Socket_listen ($socket);
#使用非阻塞模式
Socket_set_nonblock ($socket);
Echo ' Listen on port '. PORT. ' ...'. Php_eol;
$clients =array ($socket);
while (TRUE) {
$read = $clients;
$write = $except =array ();
Detects whether the socket state changes through a select system call
if (Socket_select ($read, $write, $except, 0) <1) {
Continue
}
Detect if there are clients to connect
if (In_array ($socket, $read)) {
$clients []= $newsocket =socket_accept ($socket);
Socket_write ($newsocket, "Welcome!\nthere are". Count ($clients)-1). "Client here\n");
Socket_getpeername ($newsocket, $IP);
echo "New client connected: $IP \ n";
$key =array_search ($newsocket, $read);
Unset ($read [$key]);
}
foreach ($read as $read _socket) {
$data = @socket_read ($read _socket,1024,php_normal_read);
if ($data ===false) {
If no data is taken, the client is disconnected
$key =array_search ($read _socket, $clients);
Unset ($clients [$key]);
echo "Client disconnectd.\n";
Continue
}
$data =trim ($data);
if (!empty ($data)) {
foreach ($clients as $write _socket) {
Exclude the server side and itself, and then send the data to all other clients
if ($write _socket== $socket | | $write _socket== $read _socket) {
Continue
}
Socket_write ($write _socket, "$data \ n");
}
}
}
}
Socket_close ($socket);
Start the service side:
zhxia@zhxia-pc:~/sh/php$./socket_server.php
Listen on port 9981 ...
To connect by Telnet:
zhxia@haozudb:~$ telnet 192.168.187.16 9981
Trying 192.168.187.16 ...
Connected to 192.168.187.16.
Escape character is ' ^] '.
welcome!
There are 1 client here