#!/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!');
#通过设置这个选项,进行端口的重用
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();
//通过select系统调用,检测socket的状态是否改变
if(socket_select($read,$write,$except,0)<1){
continue;
}
//检测是否有客户端来进行连接
if(in_array($socket,$read)){
$clients[]=$newsocket=socket_accept($socket);
socket_write($newsocket,"welcome!nthere are ".(count($clients)-1)." client heren");
socket_getpeername($newsocket,$ip);
echo "new client connected:$ipn";
$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){
//如果没有取到数据,说明该客户端已经断开
$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){
//排除服务器端和自身,然后将数据发送给所有的其他客户端
if($write_socket==$socket||$write_socket==$read_socket){
continue;
}
socket_write($write_socket,"$datan");
}
}
}
}
socket_close($socket);