开发网站最后进行的步骤是什么,保定建设信息网站,seo顾问服务,县城做信息网站WebSocket介绍 后端使用的是springbootnetty做websocket的服务端#xff0c;参考我其他博文 项目使用场景 开发uniapp项目时#xff0c;需要进行实时通信#xff0c;比如聊天等。需要封装一个工具类#xff0c;统一对socket进行管理。
uniapp websocket官方文档#xff1…WebSocket介绍 后端使用的是springbootnetty做websocket的服务端参考我其他博文 项目使用场景 开发uniapp项目时需要进行实时通信比如聊天等。需要封装一个工具类统一对socket进行管理。
uniapp websocket官方文档https://uniapp.dcloud.net.cn/api/request/websocket.html 代码解释
采用单例模式业务直接引入。主要是通过事件触发的形式即收到特定事件,触发对应触发器前端引入后只需要添加相对应事件监听器即可。
注意在收到数据时已经默认使用JSON去解析了一次
代码 主要通过消息通信进行操作这里定义了一个消息实体模板socketMessageTemplate
功能不齐全大家按需使用欢迎补充和讨论
// websocket.js
// 基础消息模板
const socketMessageTemplate {type: , // 消息类型timestamp: null, // 时间戳data: null, // 数据from: , // 发送者to: , // 接收者msg: , // 消息内容
};// WebSocket 管理类
class WebSocketManager {constructor({// 最大重连次数maxReconnectAttempts 3,// 重连间隔毫秒reconnectInterval 5000,// 心跳间隔毫秒heartbeatInterval 60000,} {}) {this.socket null; // WebSocket 实例this.listeners {}; // 事件监听器this.status closed; // 连接状态closed, connecting, connectedthis.heartbeatTimer null; // 心跳定时器this.reconnectAttempts 0; // 当前重连次数this.maxReconnectAttempts maxReconnectAttempts; // 最大重连次数this.reconnectInterval reconnectInterval; // 重连间隔毫秒this.heartbeatInterval heartbeatInterval; // 心跳间隔毫秒this.url null; // WebSocket 地址this.isManualClose false; // 是否为用户主动关闭}/*** 连接 WebSocket* param {string} url WebSocket 地址* param {function} successCallback 连接成功回调函数*/connect(url, successCallback () { }) {if (!url) {console.error(WebSocket 地址不能为空);return;}/* if (this.status connecting) {console.warn(WebSocket 正在连接中请稍后再试);return;} */if (this.status connected) {console.warn(WebSocket 已连接请勿重复连接);return;}this.url url;this.status connecting;this.isManualClose false; // 重置手动关闭标志this.socket uni.connectSocket({url,success: () {successCallback();console.log(WebSocket 连接请求已发送);},fail: (error) {console.error(WebSocket 连接失败, error);this.status closed;this.handleReconnect();},});this.initEventHandlers();}/*** 初始化 WebSocket 事件*/initEventHandlers() {uni.onSocketOpen(() {if (this.status connected) return; // 避免重复发送初始化消息console.log(WebSocket 连接成功);this.status connected;this.reconnectAttempts 0;this.startHeartbeat();this.triggerEvent(open);});uni.onSocketMessage(({ data }) {try {const message JSON.parse(decodeURIComponent(data));this.triggerEvent(message, message);} catch (err) {console.error(消息解析失败, err);}});uni.onSocketError((err) {console.error(WebSocket 错误, err);this.triggerEvent(error, err);});uni.onSocketClose(() {console.log(WebSocket 已关闭);this.status closed;this.stopHeartbeat();this.triggerEvent(close);if (!this.isManualClose) {this.handleReconnect();}});}/*** 处理重连逻辑*/handleReconnect() {if (this.reconnectAttempts this.maxReconnectAttempts) {this.reconnectAttempts;console.log(尝试第 ${this.reconnectAttempts} 次重连...);this.status connecting;setTimeout(() this.connect(this.url), this.reconnectInterval);} else {this.status fail;console.error(重连次数已达上限停止重连);}}/*** 启动心跳机制*/startHeartbeat() {this.stopHeartbeat(); // 避免重复启动this.heartbeatTimer setInterval(() {if (this.status connected) {this.sendMessage({ type: HEARTBEAT });// console.log(心跳检测中...);}}, this.heartbeatInterval);}/*** 停止心跳机制*/stopHeartbeat() {if (this.heartbeatTimer) {clearInterval(this.heartbeatTimer);this.heartbeatTimer null;}}/*** 添加事件监听器* param {string} event 事件类型* param {function} callback 回调函数*/addListener(event, callback) {if (!this.listeners[event]) {this.listeners[event] [];}this.listeners[event].push(callback);}/*** 移除事件监听器* param {string} event 事件类型* param {function} callback 回调函数*/removeListener(event, callback) {if (this.listeners[event]) {this.listeners[event] this.listeners[event].filter((cb) cb ! callback);}}/*** 移除所有事件监听器*/removeAllListeners() {this.listeners {}; // 清空所有事件监听器}/*** 触发事件* param {string} event 事件类型* param {any} data 回调数据*/triggerEvent(event, data null) {(this.listeners[event] || []).forEach((callback) callback(data));}/*** 发送消息 异步* param {object} message 消息内容*/async sendMessageWithRetry(message, retryCount 3, delayMs 1000) {for (let attempt 0; attempt retryCount; attempt) {if (this.status connected) {// 处理type类型全部改为大写message.type message.type.toUpperCase();const payload JSON.stringify({...socketMessageTemplate,...message,timestamp: Date.now(),});uni.sendSocketMessage({data: payload,success: () {console.log(消息发送成功, payload)},fail: (err) console.error(消息发送失败, err),});return;}console.warn(WebSocket 未连接重试中 (${attempt 1}/${retryCount})...);await new Promise((resolve) setTimeout(resolve, delayMs));}console.error(多次尝试发送消息失败WebSocket 未连接);}/*** 发送消息* param {object} message 消息内容*/sendMessage(message) {if (this.status connecting) {console.error(WebSocket 正在连接中无法发送消息);return;}if (this.status fail) {console.error(WebSocket 连接已失败无法发送消息);return;}if (this.status ! connected) {console.error(WebSocket 未连接无法发送消息);this.handleReconnect(); // 如果未连接尝试重连return;}message.type message.type.toUpperCase();const payload JSON.stringify({...socketMessageTemplate,...message,timestamp: Date.now(),});uni.sendSocketMessage({data: payload,success: () {// console.log(消息发送成功, payload)},fail: (err) {console.error(消息发送失败, err);},});}/*** 关闭 WebSocket 连接*/close() {if (this.status closed) {console.warn(WebSocket 未连接无需关闭);return;}if (this.status fail || this.status connecting) {console.warn(WebSocket 当前状态无法正常关闭重置状态);this.status closed; // 强制重置状态this.isManualClose true;return;}this.isManualClose true; // 设置为手动关闭uni.closeSocket({success: () {console.log(WebSocket 连接已关闭);this.status closed;this.stopHeartbeat();this.removeAllListeners(); // 关闭时移除所有事件监听器},fail: (err) console.error(关闭 WebSocket 失败, err),});}
}// 单例模式
const WebSocketInstance new WebSocketManager();
export default WebSocketInstance;举例
这里用uniapp 举例
templateview classcontainerviewtextWebSocket 通信示例/text/viewviewbutton clickconnectWebSocket连接 WebSocket/buttonbutton clicksendMessage发送消息/buttonbutton clickcloseWebSocket关闭 WebSocket/button/viewviewtext接收到的消息/texttext{{ receivedMessage }}/text/view/view
/templatescript setup
import { ref } from vue;
import WebSocketInstance from /utils/websocket; // 引入封装的 WebSocket 管理类
import { useWebSocket } from /utils/common;const { url } useWebSocket(12345);// 接收到的消息
const receivedMessage ref();// 连接 WebSocket
const connectWebSocket () {WebSocketInstance.connect(url);// 添加事件监听WebSocketInstance.addListener(open, () {// console.log(WebSocket 已连接);});WebSocketInstance.addListener(message, (data) {// console.log(接收到消息, data);receivedMessage.value JSON.stringify(data);});WebSocketInstance.addListener(close, () {// console.log(WebSocket 已关闭);});WebSocketInstance.addListener(error, (error) {console.error(WebSocket 错误, error);});
};// 发送消息
const sendMessage () {WebSocketInstance.sendMessageWithRetry({type: CHAT,from: user1,to: SYSTEM,msg: 你好这是一条测试消息,});
};// 关闭 WebSocket
const closeWebSocket () {WebSocketInstance.close();
};
/scriptstyle
.container {padding: 20px;
}button {margin: 10px 0;
}
/style
WebSocket介绍
WebSocket是一种在Web浏览器和Web服务器之间进行实时双向通信的协议。与HTTP协议不同的是WebSocket在建立连接后不需要通过发起HTTP请求来获取数据而是可以直接在连接上发送和接收数据。
WebSocket的特点包括以下几个方面
实时性WebSocket可以在客户端和服务器之间实时地发送消息而不需要等待服务器响应或轮询。双向通信WebSocket支持客户端和服务器之间的双向通信可以在任一方向上发送或接收消息。高效性WebSocket使用TCP协议作为传输层协议相较于HTTP协议可以减少通信的开销和延迟。跨域支持WebSocket通过在HTTP握手过程中发送特定的头部信息来支持跨域通信。推送功能WebSocket支持服务器主动向客户端推送消息不再需要客户端主动发送请求。
WebSocket的工作原理是通过建立一个持久化的连接使用HTTP协议完成初始的握手过程然后通过升级协议从HTTP协议切换到WebSocket协议。一旦建立连接客户端和服务器可以通过发送消息来进行通信而不需要再次发送HTTP请求。
WebSocket在实时聊天、实时数据更新、实时游戏等场景中具有广泛应用。由于其高效的双向通信特性WebSocket也在移动应用和物联网等领域得到了广泛的应用。 后端Websocket配合使用参考我博客其他文章好久没写博文了
文章转载自: http://www.morning.rcdmp.cn.gov.cn.rcdmp.cn http://www.morning.qpxrr.cn.gov.cn.qpxrr.cn http://www.morning.kyytt.cn.gov.cn.kyytt.cn http://www.morning.tdldh.cn.gov.cn.tdldh.cn http://www.morning.sxygc.cn.gov.cn.sxygc.cn http://www.morning.atoinfo.com.gov.cn.atoinfo.com http://www.morning.nqgff.cn.gov.cn.nqgff.cn http://www.morning.0dirty.cn.gov.cn.0dirty.cn http://www.morning.supera.com.cn.gov.cn.supera.com.cn http://www.morning.gwsfq.cn.gov.cn.gwsfq.cn http://www.morning.pwksz.cn.gov.cn.pwksz.cn http://www.morning.mgmqf.cn.gov.cn.mgmqf.cn http://www.morning.qjdqj.cn.gov.cn.qjdqj.cn http://www.morning.cmcjp.cn.gov.cn.cmcjp.cn http://www.morning.jjzxn.cn.gov.cn.jjzxn.cn http://www.morning.ryglh.cn.gov.cn.ryglh.cn http://www.morning.wbnsf.cn.gov.cn.wbnsf.cn http://www.morning.fbqr.cn.gov.cn.fbqr.cn http://www.morning.mpwgs.cn.gov.cn.mpwgs.cn http://www.morning.gtdf.cn.gov.cn.gtdf.cn http://www.morning.dnphd.cn.gov.cn.dnphd.cn http://www.morning.ksbmx.cn.gov.cn.ksbmx.cn http://www.morning.tkcct.cn.gov.cn.tkcct.cn http://www.morning.ryfqj.cn.gov.cn.ryfqj.cn http://www.morning.nrll.cn.gov.cn.nrll.cn http://www.morning.jwxmn.cn.gov.cn.jwxmn.cn http://www.morning.qpljg.cn.gov.cn.qpljg.cn http://www.morning.zrjzc.cn.gov.cn.zrjzc.cn http://www.morning.sskhm.cn.gov.cn.sskhm.cn http://www.morning.xfxnq.cn.gov.cn.xfxnq.cn http://www.morning.ryysc.cn.gov.cn.ryysc.cn http://www.morning.mmqng.cn.gov.cn.mmqng.cn http://www.morning.krdxz.cn.gov.cn.krdxz.cn http://www.morning.glrzr.cn.gov.cn.glrzr.cn http://www.morning.nqlnd.cn.gov.cn.nqlnd.cn http://www.morning.mhpkz.cn.gov.cn.mhpkz.cn http://www.morning.nccyc.cn.gov.cn.nccyc.cn http://www.morning.rttkl.cn.gov.cn.rttkl.cn http://www.morning.knryp.cn.gov.cn.knryp.cn http://www.morning.qwqzk.cn.gov.cn.qwqzk.cn http://www.morning.kcnjz.cn.gov.cn.kcnjz.cn http://www.morning.zqzzn.cn.gov.cn.zqzzn.cn http://www.morning.rxfjg.cn.gov.cn.rxfjg.cn http://www.morning.nfzzf.cn.gov.cn.nfzzf.cn http://www.morning.rpsjh.cn.gov.cn.rpsjh.cn http://www.morning.pzcqz.cn.gov.cn.pzcqz.cn http://www.morning.rwdbz.cn.gov.cn.rwdbz.cn http://www.morning.hyjpl.cn.gov.cn.hyjpl.cn http://www.morning.jbtwq.cn.gov.cn.jbtwq.cn http://www.morning.wkmpx.cn.gov.cn.wkmpx.cn http://www.morning.mzydm.cn.gov.cn.mzydm.cn http://www.morning.ndlww.cn.gov.cn.ndlww.cn http://www.morning.xsklp.cn.gov.cn.xsklp.cn http://www.morning.tztgq.cn.gov.cn.tztgq.cn http://www.morning.qmzhy.cn.gov.cn.qmzhy.cn http://www.morning.gqnll.cn.gov.cn.gqnll.cn http://www.morning.rzsxb.cn.gov.cn.rzsxb.cn http://www.morning.yghlr.cn.gov.cn.yghlr.cn http://www.morning.hxrg.cn.gov.cn.hxrg.cn http://www.morning.guanszz.com.gov.cn.guanszz.com http://www.morning.ckcjq.cn.gov.cn.ckcjq.cn http://www.morning.zkdmk.cn.gov.cn.zkdmk.cn http://www.morning.wncb.cn.gov.cn.wncb.cn http://www.morning.yqmmh.cn.gov.cn.yqmmh.cn http://www.morning.rlkgc.cn.gov.cn.rlkgc.cn http://www.morning.mtrz.cn.gov.cn.mtrz.cn http://www.morning.ylxgw.cn.gov.cn.ylxgw.cn http://www.morning.dsmwy.cn.gov.cn.dsmwy.cn http://www.morning.kpbgp.cn.gov.cn.kpbgp.cn http://www.morning.qsswb.cn.gov.cn.qsswb.cn http://www.morning.wmsgt.cn.gov.cn.wmsgt.cn http://www.morning.kyzja.com.gov.cn.kyzja.com http://www.morning.wztnh.cn.gov.cn.wztnh.cn http://www.morning.ykyfq.cn.gov.cn.ykyfq.cn http://www.morning.fhbhr.cn.gov.cn.fhbhr.cn http://www.morning.gnwpg.cn.gov.cn.gnwpg.cn http://www.morning.ncrk.cn.gov.cn.ncrk.cn http://www.morning.cwlxs.cn.gov.cn.cwlxs.cn http://www.morning.pwlxy.cn.gov.cn.pwlxy.cn http://www.morning.bsrp.cn.gov.cn.bsrp.cn