thinkphp 使用 swoole 需要安装 think-swoole compor 包,前提系统已经安装 好了 swoole pecl 拓展 tp5 的项目根目录下执行 compor 命令安装 think-swoole:
1 compor require topthink/think-swoole
话不多说,直接上代码: 新建 websocket.php 控制器: (监听端口要确认服务器放行,宝塔环境还需要添加安全组规则)
<?phpnamespace app\home\controller;u think\swoole\rver;class websocket extends rver{protected $host = '0.0.0.0'; //监听所有地址protected $port = 9501; //监听 9501 端口protected $rvertype = 'socket';protected $option = ['worker_num'=> 4, //设置启动的 worker 进程数'daemonize' => fal, //守护进程化(上线改为 true)'backlog' => 128, //listen 队列长度'dispatch_mode' => 2, //固定模式,保证同一个连接发来的数据少儿歌曲大全只会被同一个worker 处理//心跳检测:每 60 秒遍历所有连接,强制关闭 10 分钟内没有向服务器发送任何数据的连接'heartbeat_check_interval' => 60,'heartbeat_idle_time' => 600];//建立连接时回调函数public function onopen($rver,$req){$fd = $req->fd;//客户端标识$uid = $req->get['uid'];//客户端传递的用户 id$token = $req->get['token'];//客户端传递的用户登录 token//省略 token 验证逻辑......if (!$token) {$arr = array('status'=>2,'message'=>'token 已过期');$rver->push($fd, json_encode($arr));$rver->clo($fd);return;}//省略给用户绑定 fd 逻辑......echo "用户{$uid}建立了连接,标识为{$fd}\n";}//接收数据时回调函数public function onmessage($rver,$frame){$fd = $frame->fd;$message = $frame->data;//省略通过 fd 查询用户 uid 逻辑......$uid = 666;$data['uid'] = $uid;$data['message'] = '用户'.$uid.'发送了:'.$message;$data['post_time'] = date("m/d h:i",time());$arr = array('status'=>1,'message'=>'success','data'=>$data);//仅推送给当前连接用户//$rver->push($fd, json_encode($arr));//推送给全部连接用户foreach($rver->connections as $fd) {$rver->push($fd, json_encode($arr));}}//连接关闭时回调函数public function onclo($rver,$fd){echo "标识{$fd}关闭了连接\n";}}
前端演示页面: (省略控制器判断登录状态、分配数据逻辑……)
<!doctype html><html lang="en"><head><meta chart="utf-8" /><meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1" /><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,ur-scalable=no" /><title>chat</title><link rel="stylesheet" type="text/css" href="/static/liaotian/chat.css" /><script src="/static/liaotian/js/jquery.min.js"></script><script src="/static/liaotian/js/flexible.js"></script></head><body><header class="header"><a class="back" href="javascript:history.back()"></a><h5 class="tit">在线聊天</h5><a href=""><div class="right">退出</div></a></header><!-- 聊天内容 start--><div class="message"> </div><!-- 聊天内容 end--><!-- 底部 start--><div class="footer"><img id="tbtn" src="/static/liaotian/images/hua.png" alt="" /><img src="/static/liaotian/images/xiaolian.png" alt="" /><input type="text" id="msg" value="" maxlength="300"><p style="background: rgb(17, 79, 142);" id="ndbtn">发送</p></div><!-- 底部 end--></body></html><script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script><script src="https://cdn.bootcss.com/layer/3.1.0/layer.js"></script><script type="text/javascript">$(function () {var uid = 666;//当前用户 idvar token = 'abcdefg';//用户 token//判断浏览器是否支持 websocketvar supportswebsockets = 'websocket' in window || 'mozwebsocket' in window;if (supportswebsockets)ktv必点歌曲排行榜 {//建立 websocket 连接(ip 地址换成自己主机 ip)var ws = new websocket蚕妇吟("ws://127.0.0.1:9501?uid="+uid+"&token="+token);ws.onopen = function () {layer.msg('服务器连接成功',{shade:0.1,icon:1,time:600});};ws.onerror = function () {layer.msg('服务器连接失败',{shade:0.1,icon:2,time:600});};ws.onmessage = function (evt) {var data = $.parjson(evt.data);//错误提示if(data.status != 1){layer.alert(data.message,{icon:2});return;}//消息返回if (data.status==1 && data.data.message!='') {var html = "";if (data.data.uid == uid) {html += "<div style='word-break:break-all' class=\"show\"><div class=\"time\">"+data.data.post_time+"</div><div class=\"msg\"><img src=\""+data.data.head_img+"\" alt=\"\" /><p><i clas=\"学习传达msg_input\"></i>"+data.data.message+"</p></div></div>";}el{html += "<div style='word-break:break-all' class=\"nd\"><div class=\"time\">"+data.data.post_time+"</div><div class=\"msg\"><img src=\""+data.data.head_img+"\" alt=\"\" /><p><i clas=\"msg_input\"></i>"+data.data.message+"</p></div></div>";}}$(".message").append(html);ttimeout(function () {($('.message').children("div:last-child")[0]).scrollintoview();//向上滚动},100);};ws.onclo = function (res) {};//按钮发送$("#ndbtn").click(function () {var contents = $("#msg").val().trim();if(contents == null || contents == ""){layer.msg('内容为空',{shade:0.1,icon:2,time:600});return fal;}el{ws.nd(contents);$("#msg").val("");}});//回车发赵丽颖的图片送$("#msg").keydown(function (evel) {var that = $(this);if (evel.keycode == 13) {evel.cancelbubble = true;evel.preventdefault();evel.stoppropagation();var contents = that.val().trim();if(contents == null || contents == ""){layer.msg('内容为空',{shade:0.1,icon:2,time:600});return fal;}el{ws.nd(contents);that.val("");}}});}el{layer.alert("您的浏览器不支持 websocket!");}});</script>
服务器移到项目根目录开启服务: php public/index.php websocket/start 这里的路径,是因为我绑定了 home 模块为默认模块,tp5 默认情况是:php public/index.php index/websocket/start) 开启成功,查看端口已经被监听: lsof -i:9501
本文发布于:2023-04-07 18:33:41,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/d286d656ab91034eeb1e56ad2f53231a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Swoole 实现在线聊天.doc
本文 PDF 下载地址:Swoole 实现在线聊天.pdf
留言与评论(共有 0 条评论) |