阿里云网站空间今日热点头条
今天我们来整理一下webScoket,首先 webScoket是HTML5提出的一个基于TCP的一个全双工可靠通讯协议,处在应用层。很多人喜欢说webScoket是一次连接,这是误区,其实他是基于TCP的只不过将三次握手与四次挥手进行隐藏,封装。
以上是概念性的,个人理解为 webScoket是 TCP连接的升级版本,解决了数据实时推送,服务器不能主动推送数据,客户端发起多次http请求到服务器资源浏览器必须经过长时间轮询等等问题。
有人会问 怎么保证webScoket长连接的可靠性,比如前端不可控制的弱网或者服务器重启的情况下如何保证连接未中断?
其实相对应的会有一个心跳包机制来监听这个连接是否可靠。如果断开那么就会启动断线重连。
心跳包机制:定时向服务器发送特有的心跳消息,服务器收到消息后只需要返回消息,此时客户端若收到到消息表示这个连接依旧可靠,若是客户端未收到消息表示连接断开,这时候需要启动断线重连,完成一个周期。
短线重连:触发webScoket的onclose事件,重新连接服务器
让我面前端来实现一个webScoket
新建一个eventBus.js文件
// eventBus.js
// 用到了发布订阅模式
class EventBus {constructor() {// 消息中心,记录了所有的事件 以及 事件对应的处理函数this.subs = Object.create(null)}// 注册时间// 参数:1.事件名称 2.事件处理函数on(eventType, handler) {this.subs[eventType] = this.subs[eventType] || []this.subs[eventType].push(handler)}// 触发事件// 参数: 1.事件名称 2.接收的参数emit(eventType, ...ars) {if(this.subs[eventType]) {this.subs[eventType].forEach(handler => {handler(...ars)})}}
}export default new EventBus()
新增一个myWebscoket.js文件
// myWebSocket.js 单独把websocket的处理方法抽离出来
import eventBus from "./eventBus.js"
// 定义websocket消息类型
const ModeCodeEnum = {MSG: 'message', // 普通消息HEART_BEAT: 'heart_beat' // 心跳
}
class MyWebSocket extends WebSocket {constructor (url) {super(url)return this}/*** heartBeatConfig 心跳连接参数* time: 心跳时间间隔* timeout: 心跳超时间隔* reconnect: 断线重连时间间隔* isReconnect 是否断线重连*/init (heartBeatConfig, isReconnect) {this.onopen = this.openHandler // 连接成功后的回调函数this.onclose = this.closeHandler // 连接关闭后的回调 函数this.onmessage = this.messageHandler // 收到服务器数据后的回调函数this.onerror = this.errorHandler // 连接发生错误的回调方法this.heartBeatConfig = heartBeatConfig // 心跳连接配置参数this.isReconnect = isReconnect // 记录是否断线重连this.reconnectTimer = null // 记录断线重连的时间器this.startHeartBeatTimer = null // 记录心跳时间器this.webSocketState = false // 记录socket连接状态 true为已连接}// 获取消息getMessage ({ data }) {return JSON.parse(data)}// 发送消息sendMessage (data) {// 当前的this 就是指向websocketreturn this.send(JSON.stringify(data))}// 连接成功后的回调函数openHandler () {console.log('====onopen 连接成功====')// 触发事件更改按钮的状态eventBus.emit('changeBtnState', 'open')// socket状态设置为连接,做为后面的断线重连的拦截器this.webSocketState = true// 判断是否启动心跳机制if(this.heartBeatConfig && this.heartBeatConfig.time) {this.startHeartBeat(this.heartBeatConfig.time)}}// 收到服务器数据后的回调函数 messageHandler (data) {const { ModeCode, msg} = this.getMessage(data)switch (ModeCode) {case ModeCodeEnum.MSG: // 普通消息类型console.log('====onmessage 有新消息啦====', msg)breakcase ModeCodeEnum.HEART_BEAT: // 心跳this.webSocketState = trueconsole.log('====onmessage 心跳响应====', msg)break} }// 连接关闭后的回调 函数closeHandler () {console.log('====onclose websocket关闭连接====')// 触发事件更改按钮的状态eventBus.emit('changeBtnState', 'close')// 设置socket状态为断线this.webSocketState = false// 在断开连接时 记得要清楚心跳时间器和 断开重连时间器材this.startHeartBeatTimer && clearTimeout(this.startHeartBeatTimer)this.reconnectTimer && clearTimeout(this.reconnectTimer)this.reconnectWebSocket()}errorHandler () {console.log('====onerror websocket连接出错====')// 触发事件更改按钮的状态eventBus.emit('changeBtnState', 'close')// 设置socket状态为断线this.webSocketState = false// 重新连接this.reconnectWebSocket()}// 心跳初始化方法 time:心跳间隔startHeartBeat (time) {this.startHeartBeatTimer = setTimeout(() => {// 客户端每隔一段时间向服务端发送一个心跳消息this.sendMessage({ModeCode: ModeCodeEnum.HEART_BEAT,msg: Date.now()})this.waitingServer()}, time);}//在客户端发送消息之后,延时等待服务器响应,通过webSocketState判断是否连线成功waitingServer () {this.webSocketState = falsesetTimeout(() => {// 连线成功状态下 继续心跳检测if(this.webSocketState) {this.startHeartBeat(this.heartBeatConfig.time)return}console.log('心跳无响应, 已经和服务端断线')// 重新连接时,记得要先关闭当前连接try {this.close()} catch (error) {console.log('当前连接已经关闭')}// // 重新连接// this.reconnectWebSocket()}, this.heartBeatConfig.timeout)}// 重新连接reconnectWebSocket () {// 判断是否是重新连接状态(即被动状态断线),如果是主动断线的不需要重新连接if(!this.isReconnect) {return}// 根据传入的断线重连时间间隔 延时连接this.reconnectTimer = setTimeout(() => {// 触发重新连接事件eventBus.emit('reconnect')}, this.heartBeatConfig.reconnect)}
}
export default MyWebSocket
在index.html文件,引入eventBus.js和myWebSocket.js 文件
<html lang="en">
<body><div><button id="connect">连接</button><button disabled id="sendMessage">发送</button><button disabled id="close">关闭</button></div>
</body>
</html>
<script type="module">import eventBus from './eventBus.js'import MyWebsocket from './myWebSocket.js'const connectBtn = document.getElementById('connect')const sendMessageBtn = document.getElementById('sendMessage')const closeBtn = document.getElementById('close')const wsUrl = 'ws://127.0.0.1:8002'let myWS = null // // 用来记录是否连接了websocket// 处理下按钮的状态,连接情况下才能有发送和关闭功能,关闭情况下只能有连接功能const setButtonState = (state) => {switch(state) {case 'open':connectBtn.disabled = truesendMessageBtn.disabled =falsecloseBtn.disabled = falsebreakcase 'close':connectBtn.disabled = falsesendMessageBtn.disabled = truecloseBtn.disabled = true}}// 连接websocket处理函数const connectWeboSocket = () => {myWS = new MyWebsocket(wsUrl)// 调用实例对象的init函数 myWS.init({time: 4 * 1000,timeout: 2 * 1000,reconnect: 3 * 1000}, true)}// 重新连接webscoket处理 函数const reconnectWebSocket = () => {// 判断是否有初始化websocketif(!myWS) {connectWeboSocket()return}// 判断实例上的reconnectTimer 是否有值,要记得清除后再连接if(myWS && myWS.reconnectTimer) {clearTimeout(myWS.reconnectTimer)myWS.reconnectTimer = nullconnectWeboSocket()}}// 注册设置按钮样式eventBus.on('changeBtnState', setButtonState)// 注册重连websocket 事件eventBus.on('reconnect', reconnectWebSocket)// 点击连接按钮 连接websocket服务器connectBtn.addEventListener('click', reconnectWebSocket)// 点击发送按钮 向服务端传送数据sendMessageBtn.addEventListener('click', e => {myWS.sendMessage({ModeCode: "message",msg: 'hello world'})})// 点击关闭按钮 断开连接closeBtn.addEventListener('click', e => {myWS.close()myWS = null})
</script>
这样就实现了一个简易的webScoket长连接demo,这里包括心跳包机制与断线重连,自定义通信事件,实现监听与触发功能。