1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| <?php
require_once __DIR__ . '/Workerman/Autoloader.php'; use Workerman\Worker; use Workerman\Connection\AsyncTcpConnection;
$tcp_worker = new Worker("websocket://121.42.176.99:9091");
$tcp_worker->count = 1; $clients=[];
$tcp_worker->onMessage = function($connection, $data) { global $clients; if(preg_match("/^login:(\w{3,20})/i",$data,$result)) { if(!array_key_exists($connection->getRemoteIp(),$clients)) {
$clients[$connection->getRemoteIp()]=["ip"=>$connection->getRemoteIp(),"name"=>$result[1],"conn"=>$connection];
$connection->send("notice:success"); $connection->send("msg:welcome back ".$result[1]); echo $connection->getRemoteIp().":".$result[1]." login".PHP_EOL;
$users="users:".json_encode(array_column($clients,"name","ip")); foreach($clients as $ip=>$set) { $set["conn"]->send($users); }
}
} else if(preg_match("/^msg:(.*?)/isU",$data,$msgset)) { if(array_key_exists($connection->getRemoteIp(),$clients)) { echo "get msg :".$msgset[1]; } } $connection->onClose=function ($connection)//客户端主动关闭 { global $clients; unset($clients[$connection->getRemoteIp()]); }; }; $tcp_worker->onClose=function ($connection) use($clients) {
};
Worker::runAll();
|