workerman webman+GatewayWorker实现聊天室demo实例
说明
最近先来无事发现workerman的webman作为web框架很不错,想着写一个demo。于是就动手了,本人前端不太好,所以页面较丑,不要介意哈哈哈。
官方文档
https://www.workerman.net/
workerman 真的很不错,社区环境也不错,基本上有问题都有答复。有时间我也会多研究下,后面也会分享出来
重磅
demo地址: https://gitee.com/xiaoqiaoniubi/my-webman-chat
- 先下载下项目,将根目录下的webman-chat.sql 导入至数据库,数据库名称为:webman-chat。可在数据库配置文件中修改
- 执行 composer install
- windows环境:直接双击根目录下的windows.bat的文件,并在网站中访问localhost:8787
- linux环境:防火墙等开放7272端口(websocket),在根目录上执行 php start.php start
代码片段
- 服务端监听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);

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

被折叠的 条评论
为什么被折叠?



