thinkphp使用swoole需要安装 think-swoole compor包,前提系统已经安装好了swoole pecl 拓展*
tp5的项目根目录下执行compor命令安装think-swoole:
compor require topthink/think-swoole
话不多说,直接上代码:
新建websocket.php控制器
(监听端口要确认服务器放行,宝塔环境还需要添加安全组规则)
1 <?php 2 3 namespace app\home\controller; 4 u think\swoole\rver; 5 class websocket extends rver 6 { 7 protected $host = '0.0.0.0'; //监听所有地址 8 protected $port = 9501; //监听9501端口 9 protected $rvertype = 'socket';10 protected $option = [ 11 'worker_num'=> 4, //设置启动的worker进程数12 'daemonize' => fal, //守护进程化(上线改为true)13 'backlog' => 128, //listen队列长度14 'dispatch_mode' => 2, //固定模式,保证同一个连接发来的数据只会被同一个worker处理15 16 //心跳检测:每60秒遍历所有连接,强制关闭10分钟内没有向服务器发送任何数据的连接17 'heartbeat_check_interval' => 60,18 'heartbeat_idle_time' => 60019 ];20 21 //建立连接时回调函数22 public function onopen($rver,$req)23 {24 $fd = $req->fd;//客户端标识25 $uid = $req->get['uid'];//客户端传递的用户id26 $token = $req->get['token'];//客户端传递的用户登录token27 28 //省略token验幼儿园感谢信证逻辑......29 if (!$token) {30 $arr = array('status'=>2,'message'=>'token已过期');31 $rver->push($fd, json_encode($arr));32 $rver->clo($fd);33 return;34 }35 //省略给用户绑定fd逻辑......36 echo "用户{$uid}建立了连接,标识为{$fd}\n";37 }38 39 //接收数据时回调函数40 public function onmessage($rver,$frame)41 {42 $fd = $frame->fd;43 $message = $frame->data;44 45 //省略通过fd查询用户uid逻辑......46 $uid = 666;47 $data['uid'] = $uid;48 $data['message'] = '用户'.$uid.'发送了:'.$message;49 $data['post_time'] = date("m/d h:i",time());50 $arr = array('status'=>临别赠言给同学;1,'message'=>'success','data'=>$data);51 52 //仅推送给当前连接用户53 //$rver->push($fd, json_encode($arr));54 55 //推送给全部连接用户56 foreach($rver->connections as $fd) {57 $rver->push($fd, json_encode($arr));58 } 59 }60 61 //连接关闭时回调函数62 public function onclo($rver,$fd)63 {64 echo "标识{$fd}关闭了连接\n";65 }66 }
前端演示页面:
(省略控制器判断登录状态、分配数据逻辑……)
1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta chart="utf-8" /> 5 <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1" /> 6 <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,ur-scalable=no" /> 7 <title>chat</title> 8 <link rel="stylesheet" type="text/css" href="/static/liaotian/chat.css" /> 9 <script src="/static/liaotian/js/jquery.min.js"></script> 10 <script src="/static/liaotian/js/flexible.js"></script> 11 </head> 12 <body> 13 <header class="header"> 14 <a class="back" href="javascript:history.back()"></a> 15 <h5 class="tit">在线聊天</h5> 16 <a href=""><div class="right">退出</div></a> 17 </header> 18 19 <!-- 聊天内容 start--> 20 <div class="message"> </div> 21 <!-- 聊天内容 end--> 22 23 <!-- 底部 start--> 24 <div class="footer"> 25 <img id="tbtn" src="/static/liaotian/images/hua.png" alt="" /> 26 <img src="/static/liaotian/images/xiaolian.png" alt="" /> 27 <input type="text" id="msg" value="" maxlength="300"> 28 <p style="background: rgb(17, 79, 142);" id="ndbtn">发送</p> 29 </div> 30 <!-- 底部 end--> 31 </body> 32 </html> 33 <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script男子举重> 34 <script src="https://cdn.bootcss.com/layer/3.1.0/layer.js"></script> 35 <script type="text/javascript"> 36 $(function () { 37 var uid = 666;//当前用户id 38 var token = 'abcdefg';//用户token 39 40 //判断浏览器是否支持websocket 41 var supportswebsockets = 'websocket' in window || 'mozwebsocket' in window; 42 if (supportswebsockets) { 43 //建立websocket连接(ip地址换成自己主机ip) 44 var ws = new websocket("ws://127.0.0.1:9501?uid="+uid+"&token="+token); 45 ws.onopen = function () { 46 layer.msg('服务器连接成功',{shade:0.1,icon:1,time:600}); 47 }; 48 ws.onerror = function () { 49 layer.msg('服务器连接失败',{shade:0.1,icon:2,time:600}); 50 }; 51 ws.onmessage = function (evt) { 52 var data = $.parjson(evt.data); 53 //错误提示 54 if(data.status != 1){ 55 layer.alert(data.message,{icon:2}); 56 return; 57 } 58 //消息返回 59 if (data.status==1 && data.data.message!='') { 60 var html = ""; 61 if (data.data.uid == uid) { 62 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>"; 63 }el{ 64 html += "<div style='word-break:break-all' class=\"s散光的症状end\"><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>"; 65 } 66 } 67 $(".message").append(html); 68 ttimeout(function () { 69 ($('.message').children("div:last-child")[0]).scrollintoview();//向上滚动 70 },100); 71 }; 72 ws.onclo = function (res) { 73 74 }; 75 //按钮发送 76 $("#ndbtn").click(function () { 77 var contents = $("#msg").val().trim(); 78 if(contents == null || contents == ""){ 79 layer.msg('内容为空',{shade:0.1,icon:2,time:600}); 80 return fal; 81 }el{ 82 ws.nd(contents); 83 $("#msg").val(""); 84 } 85 }); 86 //回车发送 87 $("#msg").keydown(function (evel) { 88 var that = $(this); 89 if (evel.keycode == 13) { 90 evel.can林地承包celbubble = true; 91 evel.preventdefault(); 92 evel.stoppropagation(); 93 var contents = that.val().trim(); 94 if(contents == null || contents == ""){ 95 layer.msg('内容为空',{shade:0.1,icon:2,time:600}); 96 return fal; 97 }el{ 98 ws.nd(contents); 99 that.val("");100 }101 }102 });103 }el{104 layer.alert("您的浏览器不支持 websocket!");105 }106 });107 </script>108
服务器移到项目根目录开启服务:
php public/index.php websocket/start
这里的路径,是因为我绑定了home模块为默认模块,tp5默认情况是:php public/index.php index/websocket/start)
开启成功,查看端口已经被监听:
lsof -i:9501
本文发布于:2023-04-07 19:50:47,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/fc31ed91904c933c0fb2d0ed6816a46c.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Swoole跟thinkphp5结合开发WebSocket在线聊天通讯系统.doc
本文 PDF 下载地址:Swoole跟thinkphp5结合开发WebSocket在线聊天通讯系统.pdf
留言与评论(共有 0 条评论) |