workerman webman+GatewayWorker实现聊天室demo实例

本文介绍使用 Workerman 的 Webman 框架搭建聊天应用的过程,包括服务端 WebSocket 监听实现及客户端交互代码。通过具体代码示例展示了用户登录验证、房间加入、消息发送等功能。

workerman webman+GatewayWorker实现聊天室demo实例

说明

最近先来无事发现workerman的webman作为web框架很不错,想着写一个demo。于是就动手了,本人前端不太好,所以页面较丑,不要介意哈哈哈。

官方文档

https://www.workerman.net/

workerman 真的很不错,社区环境也不错,基本上有问题都有答复。有时间我也会多研究下,后面也会分享出来

重磅

demo地址: https://gitee.com/xiaoqiaoniubi/my-webman-chat

  1. 先下载下项目,将根目录下的webman-chat.sql 导入至数据库,数据库名称为:webman-chat。可在数据库配置文件中修改
  2. 执行 composer install
  3. windows环境:直接双击根目录下的windows.bat的文件,并在网站中访问localhost:8787
  4. linux环境:防火墙等开放7272端口(websocket),在根目录上执行 php start.php start

代码片段

  1. 服务端监听websocket:
    位置:根目录/plugin/webman/gateway/Events.php
    public static function onWebSocketConnect($client_id, $data)
    {
   
   
        // 拿到连接时携带的token 查询uid
        $getData = $data['get'];
        $userModel = new User();
        $userInfo = $userModel -> getUserInfoByToken($getData['token']);
        if (empty($userInfo)) {
   
    // token过期
            send($client_id,'账号信息错误,请重新登录',[
                'type' => MsgType::LOGIN_ERROR,
            ]);
            sleep(1); // 延迟一秒断开链接
            return Gateway::closeClient($client_id);
        }
        $uid = $userInfo -> id;
        // 重复上线验证
        if (count(Gateway::getClientIdByUid($uid)) > 0) {
   
   
            send($client_id,'当前账号已在线,请换个账号',[
                'type' => MsgType::ERROR,
            ]);
            sleep(1); // 延迟一秒断开链接
            return Gateway::closeClient($client_id);
        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值