好用的websocket 心跳重连js脚本
<script> var wsUrl = "{$ws_url}"; var ws = null; // WebSocket 对象 var heartbeatTimer = null; // 心跳定时器 var isReconnect = true; // 是否自动重连 function createWebSocket() { if ("WebSocket" in window) { ws = new WebSocket(wsUrl); // WebSocket 打开事件 ws.onopen = function () { console.log("WebSocket 已成功连接"); // 开始心跳定时器 startHeartbeat(); }; // WebSocket 收到消息事件 ws.onmessage = function (e) { console.log("WebSocket 收到消息:" + e.data); var data = e.data; try { JSON.parse(data); data = JSON.parse(data) ? JSON.parse(data) : data; } catch { console.log('ws接收到非对象数据', data); return true; } var type = data.type || ''; switch(type){ case 'get_client_id': bindUid(data.data.client_id); break; case "new_notice": break; case "notice_panel": noticePanel.render(resdata.notice_data, resdata.wait_data); break; } }; // 发生错误回调 ws.onerror = function (e) { // window.top.notify.warning("新客户提醒、一键拨号服务异常"); console.log('WebSocket错误:', e); } // WebSocket 关闭事件 ws.onclose = function () { console.log("WebSocket 已关闭"); // 停止心跳定时器 stopHeartbeat(); // 断线后自动重连 if (isReconnect) { setTimeout(function () { console.log("WebSocket 尝试重新连接"); createWebSocket(); }, 3 * 1000); } }; } else { console.log("该浏览器不支持 WebSocket"); } } // 发送消息 function sendMessage(message) { if (ws != null && ws.readyState == WebSocket.OPEN) { ws.send(message); console.log("WebSocket 发送消息:" + message); } else { console.log("WebSocket 连接没有建立或已关闭"); } } // 开始心跳定时器 function startHeartbeat(interval) { interval = interval || 30; heartbeatTimer = setInterval(function () { sendMessage("heartbeat"); }, interval * 1000); } // 停止心跳定时器 function stopHeartbeat() { clearInterval(heartbeatTimer); } //绑定uid function bindUid(client_id) { console.log('WebSocket 绑定客户端id' + client_id); var bindUrl = "{:url('socket/bindPcUserClientId')}"; $.post(bindUrl, {client_id: client_id}, function(data){ console.log(data); }, 'json'); } // 启动 WebSocket 连接 createWebSocket(); </script>
后端代码
/** * 绑定后台pc客户端id */ public function bindPcUserClientId() { if (false === $this->request->isPost()) { $this->error('非法操作'); } $adminAuth = Auth::instance(); if (!$adminAuth->isLogin()) { $this->error('请登录后操作'); } $client_id = $this->request->post('client_id','','trim'); $group_id = Env::get('group.group_id', 1); //集团id $organise_id = $this->auth_belong_organise_id; $admin_id = $this->auth->id; $band_admin_id = md5($group_id .'|'. $organise_id .'|'. $admin_id); Gateway::bindUid($client_id, $band_admin_id); $this->success('绑定成功','',[ 'server_id'=> $band_admin_id]); }