The following is a simple message processing server implemented through the socket extension module of php: bound to a local port, listening to client connections, receiving data, and forwarding to all clients other than the sender
Socket_server.php
Copy codeThe Code is as follows :#! /Usr/bin/env php
<? Php
// Author: zhxia
If (! Extension_loaded ('buckets ')){
Die ('the sockets extension is not loaded! ');
}
Const PORT = 9981;
$ Socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ('socket create error! ');
# Port reuse by setting this option
Socket_set_option ($ socket, SOL_SOCKET, SO_REUSEADDR, 1 );
Socket_bind ($ socket, 0, PORT );
Socket_listen ($ socket );
# Use non-blocking mode
Socket_set_nonblock ($ socket );
Echo 'Listen on port'. port. '...'. PHP_EOL;
$ Clients = array ($ socket );
While (TRUE ){
$ Read = $ clients;
$ Write = $ response T = array ();
// Call the select system to check whether the socket status changes
If (socket_select ($ read, $ write, $ response T, 0) <1 ){
Continue;
}
// Check whether a client is connected
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 obtained, 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 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 server:
Zhxia @ zhxia-pc :~ /Sh/php $./socket_server.php
Listen on port 9981...
Connect via 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