简单的聊天室代码

前提

安装swoole

前端




    
    聊天室



亮亮的聊天室

姓名:

后台

users = [];
$server->on('open', function (swoole_websocket_server $server, $request) {
    $server->users[$request->fd]['id'] = $request->fd;
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
    $data = json_decode($frame->data,true);
    if($data['type'] == 1){
        $server->users[$frame->fd]['name']=$data['name'];
        $server->push($frame->fd,'欢迎您('.$data['name'].')进入聊天室!');
    }else{
        foreach($server->users as $v){
            $server->push($v['id'], $server->users[$frame->fd]['name'].'说:'.$data['content']);
        }
    }
});
$server->on('close', function ($ser, $fd) {
    file_put_contents('qq.txt',$server->users[$frame->fd],FILE_APPEND);
    unset($server->users[$frame->fd]);
});
$server->start();
on('open', function (swoole_websocket_server $server, $request) use (&$clientFds) {
   # echo "server: handshake success with fd{$request->fd}\n";
   # 将所有客户端连接标识,握手成功后保存到数组中
   $clientFds[] = $request->fd;
});
# 收到消息 触发回调函数
$server->on('message', function (swoole_websocket_server $server, $frame) use (&$clientFds) {
   # echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
   # $server->push($frame->fd, "this is server");
   # 当有用户发送信息,发送广播通知所有用户
   foreach ($clientFds as $fd) {
      $server->push($fd, $frame->data);
   }
});
# 关闭连接 触发回调函数
$server->on('close', function ($ser, $fd) use (&$clientFds) {
   # echo "client {$fd} closed\n";
   # 关闭会话 销毁标识 fd
   # 根据 value 去数组中找对应的 key
   $res = array_search($fd, $clientFds, true);
   unset($clientFds[$res]);
});
# 启动 websocket 服务
$server->start();



   
   WebSocket 聊天室



你可能感兴趣的:(php)