Class socket{private $_socket; Private $_domain = Af_inet; Private $_type = Sock_stream; Private $_protocol = sol_tcp; Private $_clients = []; Private $_max_clients = 10; Public Function __construct () {if (!extension_loaded (' Sockets ')} {die (' The sockets extension are not Loaded! '); if ($this->_socket = $this->create ($this->_domain, $this->_type, $this->_protocol)) < 0) { $this->error ($this->_socket); }} Public function Start ($IP, $port) {if ($res = $this->set_option ()) < 0) {$this-> ; error ($res); if ($res = $this->bind ($ip, $port)) < 0) {$this->error ($res); } if ($res = $this->listen (5)) < 0) {$this->error ($res); } #使用非阻塞模式 Socket_set_nonblock ($this->_socket); echo "Listen on port". $port. "..." . Php_eol; $clients = Array ($this->_socket); while (true) {$this->_clients = $clients; $write = []; $except = []; if (Socket_select ($this->_clients, $write, $except, 0) < 1) {continue; } if (In_array ($this->_socket, $this->_clients)) {$clients [] = $connection = $this->co Nnect ()//if (($clients + 1) > $this->_max_clients) {//echo "Too many clients. ." . php_eol;//} else {$this->send ($connection, "Welcome!\nthere is". (Count ($clients)-1). "Client here\n"); Socket_getpeername ($connection, $client _ip); echo "New client connected: $client _ip\n"; $key = Array_search ($connection, $this->_clients); unset ($this->_clients[$key]);/}} foreach ($this->_clients as $client) { $receive = $this->receive ($client); if ($receive ===false) {$key =array_search ($client, $clients); Unset ($clients [$key]); echo "Client disconnected.\n"; Continue } $receive = Trim ($receive); if (!empty ($receive)) {foreach ($clients as $send _socket) {if ($send _socket== $this- >_socket| | $send _socket== $client) {continue; } $this->send ($send _socket, $this->_socket. " > ". $client." > "." $receive \ n "); }}} $this->close (); Public function bind ($IP, $port) {socket_bind ($this->_socket, $ip, $port); } Public Function Listen ($max _clients) {Socket_listen ($this->_socket, $max _clients); } Public Function connect () {return socket_accept ($this->_socket); The Public function send ($connection, $msg) {socket_write ($connection, $msg); Public function receive ($client) {return Socket_read ($client, 819292, Php_normal_read); The Public Function error ($resource) {echo socket_strerror ($resource). Php_eol; Public function Close () {socket_close ($this->_socket); Public Function Create ($domain = af_inet, $type = sock_stream, $protocol = sol_tcp) {return socket_create ( $domain, $type, $protocol); } public Function Set_option () {socket_set_option ($this->_socket,sol_socket,so_reuseaddr,1); }}
Demo
Ini_set ("Display_errors", 1); Include_once Inc_path. "class/socket.class.php"; $socket = new socket (); $socket->start ("192.168.2.113", 1371);
Php+socket Chat Room (telnet command Debug)