$(function () { var uid = 1;//用户id ..._tp5.1 im">
赞
踩
代码是从其他地方C/V过来的,具体网址(https://blog.csdn.net/msllws/article/details/84405127),在这记录并以个人观点阐述一下
swoole 来做IM的逻辑不难,懂的人不会看,不懂的人看不懂,我就不写在这里了,体现在代码里吧
在前端页面引入一个jQ库(为了支持以下jq代码)
<script type="text/javascript"> $(function () { var uid = 1;//用户id var token = 'token123';//token //判断浏览器是否支持WebSocket var supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window; if (supportsWebSockets) { //建立WebSocket连接(ip地址换成服务器的ip) var ws = new WebSocket("ws://***.***.***.***:9501?uid="+uid+"&token="+token); ws.onopen = function () { alert('服务器连接成功'); }; ws.onerror = function () { alert('服务器连接失败'); }; ws.onmessage = function (result) { var data = jQuery.parseJSON(result.data); //消息返回 if (data.message!='') { var html = ""; if (data.uid == uid) { html += "<div >我发的"+data.time+":"+data.message+"</div>"; }else{ html += "<div >对方发的"+data.time+":"+data.message+"</div>"; } } $(".message").append(html); }; ws.onclose = function (res) { }; //按钮发送 $("#sendBtn").click(function () { var contents = $("#msg").val().trim(); if(contents == null || contents == ""){ layer.msg('内容为空',{shade:0.1,icon:2,time:600}); return false; }else{ ws.send(contents); $("#msg").val(""); } }); }else{ layer.alert("您的浏览器不支持 WebSocket!"); } }); </script>
html:
<div class="message"> </div>
<input type="text" id="msg" value="" maxlength="300"><p id="sendBtn">发送</p>
php:(controller里加Websocket.php)
class Websocket extends Server { protected $host = '0.0.0.0'; //监听所有地址 protected $port = 9501; //监听9501端口 protected $serverType = 'socket'; protected $option = [ 'worker_num' => 4, //设置启动的Worker进程数 'daemonize' => false, //守护进程化(上线改为true) 'backlog' => 128, //Listen队列长度 'dispatch_mode' => 2, //固定模式,保证同一个连接发来的数据只会被同一个worker处理 //心跳检测:每60秒遍历所有连接,强制关闭10分钟内没有向服务器发送任何数据的连接 'heartbeat_check_interval' => 60, 'heartbeat_idle_time' => 600 ]; //建立连接时回调函数 public function onOpen($server, $req) { $fd = $req->fd;//客户端标识 $uid = $req->get['uid'];//客户端传递的用户id $token = $req->get['token'];//客户端传递的用户登录token //省略token验证逻辑...... if (!$token) { $arr = array('status' => 2, 'message' => 'token已过期'); $server->push($fd, json_encode($arr)); $server->close($fd); return; } //省略给用户绑定fd逻辑...... echo "用户{$uid}建立了连接,标识为{$fd}\n"; } //接收数据时回调函数 public function onMessage($server, $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); //仅推送给当前连接用户 //$server->push($fd, json_encode($arr)); //推送给全部连接用户 foreach ($server->connections as $fd) { $server->push($fd, json_encode($arr)); } } //连接关闭时回调函数 public function onClose($server, $fd) { echo "标识{$fd}关闭了连接\n"; } }
然后linux命令php public/index.php index/Websocket/start 开启服务端监听
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。