123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace app\act\socket;
- use think\worker\Server;
- class Worker extends Server
- {
- protected $clients = [];
- protected $socket = 'websocket://0.0.0.0:2346';
-
- public function onMessage($connection, $data)
- {
- if (preg_match('/^login:(\w{3,20})/i', $data, $result)) {
- $ip = $connection->getRemoteIp();
- $port = $connection->getRemotePort();
- if (!array_key_exists($ip, $this->clients)) {
- $this->clients[$ip.':'.$port] = ['ipp'=>$ip.':'.$port,'name'=>$result[1],'conn'=>$connection];
-
- $connection->send('notice:success');
- $connection->send('msg:你好'.$result[1]);
- echo $ip . ':'.$port . '--------' .$result[1] . 'login' . PHP_EOL;
-
-
-
-
- $users = 'users:'.json_encode(array_column($this->clients,'name','ipp'));
- foreach($this->clients as $ip=>$client){
-
- $client['conn']->send($users);
- }
- }
- } elseif(preg_match('/^msg:(.*?)/isU',$data,$megset)) {
-
- if(array_key_exists($connection->getRemoteIp(),$this->clients)) {
- echo '用户:' . $connection->getRemoteIp() . '发的消息是' . $megset[1] . PHP_EOL;
- if($megset[1] == 'nihao'){
- $connection->send('msg:nihao'.$this->clients[$connection->getRemoteIp()]);
- }
-
- }
- } elseif(preg_match('/^dian:\<(.*?)\>:(.*?)/isU',$data,$meg)) {
-
- $ipp = $meg[1];
- $msg = $meg[2];
- $name = $this->clients[$ipp]['name'];
- echo "<pre>";
- var_dump($name);
- if(array_key_exists($ipp,$this->clients)){
- $this->clients[$ipp]['conn']->send('dian:'.$msg);
- echo $ipp.'==>'.$msg.PHP_EOL;
- }
- }
- }
-
- public function onConnect($connection)
- {
- }
-
- public function onClose($connection)
- {
- unset($this->clients[$connection->getRemoteIp()]);
- }
-
- public function onError($connection, $code, $msg)
- {
- echo "error $code $msg\n";
- }
-
- public function onWorkerStart($worker)
- {
- }
- }
|