首页 > PHP技术 > swoole > 实例分享||使用swoole快速搭建websocket,实现简单聊天
2021
11-30

实例分享||使用swoole快速搭建websocket,实现简单聊天

本文将从实例出发,教大家怎么使用swoole快速搭建服务器,实现简易聊天。


我使用的环境是

php-fpm :  7.2.8
nginx   :  1.19.6
redis   :  5.0.3
服务端直接copy文档实例并添加自己的业务逻辑


$this->server = new Server("0.0.0.0", 9501);

        $this->server->set([
            'worker_num'               =>  1,
            'heartbeat_check_interval' =>  30,
            'heartbeat_idle_time'      => 62,
            'daemonize'                => true, //开启守护进程
            'log_file'                 => '/opt/local/swoole_log/ws_log'
        ]);
        $this->server->on('message', function (Server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
            $object = json_decode($frame->data, true);
            if (!empty($object)) {
                $this->push($object);
            }
            $this->disposeMember($frame->fd, true, $object['nickname']);
        });

        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
            $nickname = $this->disposeMember($fd, false);
            if (!empty($nickname)) {
                $this->push([
                    'nickname' => $nickname, 
                    'content'  => '退出了聊天室',
                    'type'     => 1,
                    'time'     => date("Y-m-d H:i:s", time())
                ], null, $fd);
            }
        });

        $this->server->start();


客服端使用js的websocket接口并添加自己的业务逻辑


initWebSocket: function () {
      var that = this;
      try {
        if (window.WebSocket){  
          that.server = new WebSocket(that.ws_server);
          // 连接
          that.server.addEventListener('open', (event) => {
            // console.log(that.lockReconnect);
              if (that.is_newserver) {
                that.sendMessageCopy(1, '进入了聊天室');
                that.is_newserver = false;
              };
              that.start();
          });
          // 关闭
          that.server.addEventListener('close', (event) => {
            console.log('close');
            that.reconnect();
          });

          that.server.onmessage = function (evt) {
            that.reset();
            let test = JSON.parse(evt.data);
            that.chatList.push({
              type    : test.type,
              nickname: test.nickname, 
              content : test.content,
              avatar  : test.avatar,
              time    : test.time
            });
              console.log('Retrieved data from server: ' + evt.data);
          };

          that.server.onerror = function (evt, e) {
              console.log('Error occured: ' + evt.data);
          };

        }else{  
            console.log("您的浏览器不支持WebSocket");  
        }  
      } catch(e) {
        //重连
        reconnect(that.ws_server);
      }
    },
聊天室效果


以上就是“实例分享||使用swoole快速搭建websocket,实现简单聊天”的详细内容,想要了解更多swoole教程欢迎持续关注编程学习网

扫码芷若 获取免费视频学习资料

编程学习

查 看2019高级编程视频教程免费获取