第三课:workerman之简易聊天室

代码依赖

第三课:workerman之简易聊天室_第1张图片
image.png

服务端代码

count = 1;
$clients = [];
// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data)
{
    global $clients;
    echo $data.PHP_EOL;
    if (preg_match('/^login:(\w{3,20})/i', $data,$result)) {
        if (!array_key_exists($connection->getRemoteIp().':'.$connection->getRemotePort(), $clients)) {

            $clients[$connection->getRemoteIp().':'.$connection->getRemotePort()] = ['fd'=>$connection->getRemoteIp().':'.$connection->getRemotePort(),'name'=>$result[1],'conn'=>$connection];

            $connection->send("notice:success");//
            $connection->send("msg:welcome back ".$result[1]);
            
            $allUser = "user:".json_encode(array_column($clients, 'name','fd'));
            foreach ($clients as $value) {
                $value['conn']->send($allUser);
            }
        }
    } else if(preg_match("/^msg:(.*?)/isU",$data,$msgset)) {//代表 是客户端发送普通消息
        if(array_key_exists($connection->getRemoteIp(),$clients)) //必须已经认证过得客户端
        {
            echo "get msg :".$msgset[1];
        }
    } else if (preg_match("/^chat:\<(.*?)\>:(.*?)/isU",$data,$msgset)) {
        var_dump($msgset);
        $ipp = $msgset[1];
        $msg = $msgset[2];
        if (array_key_exists($ipp, $clients)) {
            $clients[$ipp]['conn']->send("msg:".$msg);
        }
    }
    $connection->onClose=function ($connection)//客户端主动关闭
    {
        global $clients;
        unset($clients[$connection->getRemoteIp().':'.$connection->getRemotePort()]);
        $allUser = "user:".json_encode(array_column($clients, 'name','fd'));
        foreach ($clients as $value) {
            $value['conn']->send($allUser);
        }        
    };  

};

// 运行worker
Worker::runAll();

客户端代码




    chat room



    
message
聊天内容:
当前用户:
聊天对象:

运行截图

第三课:workerman之简易聊天室_第2张图片
image.png

你可能感兴趣的:(第三课:workerman之简易聊天室)