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
#! /Usr/bin/env php <? Php // author: zhxiaif (! 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! '); # Set this option to reuse socket_set_option ($ socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind ($ socket, 0, PORT ); socket_listen ($ socket); # use the 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 (); // called by the select system, check whether the socket status changes if (socket_select ($ read, $ write, $ response T, 0) <1) {continue ;} // check whether a client is connected to if (in_array ($ sock Et, $ 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 has been 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, 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