count = 1; $count=0; /** * 同步登录用户列表 */ function syncUsers($clients='') { $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); fwrite($myfile, $clients); fclose($myfile); } function sel_user() { $myfile = fopen("newfile.txt", "r") or die("Unable to open file!"); $a=fread($myfile,filesize("newfile.txt")); fclose($myfile); return json_decode($a,'true'); } // 当收到客户端发来的数据后 $ws_worker->onMessage = function($connection, $data) { $connection->lastMessageTime = time(); global $clients; global $count; if(preg_match('/^admin_login:(\w{2,20})/i',$data,$result)){ //代表是客户端认证 $ip=$result[1]; //通过全局变量获得db实例 $connection->send('admin_login_ip '.$ip); //普通消息 echo $ip.'==>'.$result[1].'==>login2'.PHP_EOL; //这是为了演示,控制台打印信息 // $GLOBALS['rt'][$ip] = ['ip'=>$ip,'conn'=>$connection]; $GLOBALS['clients'][$ip] = ['ip'=>$ip,'conn'=>$connection]; //$abc->add($ip,['ip'=>$ip,'conn'=>$connection]); //$ws_worker->m_iparry[$ip]=['ip'=>$ip,'conn'=>$connection]; //$connection->id=$ip; $count++; }elseif(preg_match('/^user_login:(\w{2,20})/i',$data,$result)){ //代表是客户端认证 //通过全局变量获得db实例 $ip=$result[1]; $connection->send('user_login_ip'.$ip); //普通消息 echo $ip .'==>'.$result[1].'==>login2'.PHP_EOL; //这是为了演示,控制台打印信息 // $GLOBALS['rt'][$ip] = ['ip'=>$ip,'conn'=>$connection]; $GLOBALS['clients'][$ip] = ['ip'=>$ip,'conn'=>$connection]; //$abc->add($ip,['ip'=>$ip,'conn'=>$connection]); //$ws_worker->m_iparry[$ip]=['ip'=>$ip,'conn'=>$connection]; $count++; //$connection->id=$ip; }elseif (preg_match('/^chat:\<(.*?)\>:(.*?)/isU',$data,$msgset)){ //客服发送消息 $admin_ip = $msgset[1]; $msg = $msgset[2]; $GLOBALS['clients'][$admin_ip]['conn']->send('msg:'.$msg); //$abc->gett($admin_ip)['conn']->send('msg:'.$msg); //$ws_worker->m_iparry[$admin_ip]['conn']->send('msg:'.$msg); //$ws_worker->connections[$admin_ip]->send('msg:'.$msg); } elseif (is_array(json_decode($data,'true'))) { //vip发送消息 $res=json_decode($data,'true'); $admin_ip=$res['admin_ip']; //$abc->gett($admin_ip)['conn']->send($data); //$ws_worker->m_iparry[$admin_ip]['conn']->send($data); //$ws_worker->connections[$admin_ip]->send('msg:'.$data); $GLOBALS['clients'][$admin_ip]['conn']->send('msg:'.$data); } //设置连接的onClose回调 $connection->onClose = function($connection) //客户端主动关闭 { // unset($GLOBALS[$connection->getRemoteIp().':'.$connection->getRemotePort()]); //客户端关闭 //即退出登录,也需要更新用户列表数据 //syncUsers(); echo "connection closed\n"; }; echo $count."\n"; //var_dump($GLOBALS['clients']); }; // 进程启动后设置一个每秒运行一次的定时器 $ws_worker->onWorkerStart = function($ws_worker) { Timer::add(1, function()use($ws_worker){ $time_now = time(); foreach($ws_worker->connections as $connection) { // 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间 if (empty($connection->lastMessageTime)) { $connection->lastMessageTime = $time_now; continue; } // 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接 if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) { $connection->close(); } } }); }; // 运行worker Worker::runAll();