1、ServerTimer.php 代码:
onConnect = function ($connection) { // 每10s 检查客户端是否有name属性 Timer::add(10, function () use ($connection) { if (!isset($connection->name)) { $connection->close("auth timeout and close"); } }, null, false);};$worker->onMessage = function ($connection, $data) { if (!isset($connection->name)) { $data = json_decode($data,true); if (!isset($data['name']) || !isset($data['password'])) { return $connection->close("auth fail and close"); } // 如果客户端name存在,mysql,这里使用动态给对象赋值属性name,标记该对象已经通过验证 $connection->name = $data['name']; // 广播给所有用户,该用户加入 return broadcast($connection->name . " join \n"); } // 简单的连接器 return broadcast($connection->name . ' said : ' . $data);};function broadcast($msg){ // 引入$worker 对象 global $worker; // $worker->connections 为客户端连接的所有对象 foreach ($worker->connections as $connection) { if (!isset($connection->name)) { //忽略掉 continue; } $connection->send($msg); }}$worker::runAll();/
2、开启服务
3、打开谷歌浏览器测试
(1)没有携带name和password
(2)携带name和password
(3)两个客户端互相通信
客户端001
客户端002