在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
webSocket方法
- ws.send() – 向服务器发送数据
- ws.close() – 关闭连接
webSocket事件
- ws.onopen – 建立连接时触发
- ws.onmessage – 客户端接收服务端数据时触发
- ws.onerror – 通信错误时触发
- ws.onclose – 连接错误时触发
// ws 模块 npm install ws
const WebSocket = require('ws')
function getTestDm () {
let url = `wss://ddss/v3/${branch}`
const ws = new WebSocket(url)
const content = {
'refText': '111',
}
ws.on('open', function open () {
ws.send(JSON.stringify(content))
})
ws.on('error', function (error) {
console.log('ws-error-', error)
})
ws.on('close', function (close) {
console.log('close=', close)
})
ws.on('message', function (message) {
let messageJson = JSON.parse(message)
ws.send(JSON.stringify(content)) // 接收到信息后循环发送信息
ws.close() // 关闭连接
})
}
websocket 心跳机制
如果代理服务器在60秒内未传输任何数据,则连接将关闭。
1、可以使用proxy_read_timeout指令来增加此超时时间 。(增大nginx的proxy_read_timeout 时间设置)
2、可以将代理服务器配置为定期发送WebSocket ping帧以重置超时并检查连接是否仍然有效。
案例:websocket默认60s,无任何返回信息自动断开。案例中请求返回信息是120s(read_timeout: 120s),针对这一问题将读取时间过长得情况下如何保持之间通信不自动断开
解决方案:该项目直接打包出版本(nginx配置不适用),只剩下方案二,ping
// ws 模块 npm install ws
const WebSocket = require('ws')
function getTestDm () {
let url = `wss://ddss/v3/${branch}`
const ws = new WebSocket(url)
const content = {
'refText': '111',
}
ws.on('open', function open () {
heartbeat.reset() // 关闭心跳!!!
heartbeat.start() // 开启心跳!!!
ws.send(JSON.stringify(content))
})
ws.on('error', function (error) {
heartbeat.reset() // 关闭心跳机制!!!
console.log('ws-error-', error)
})
ws.on('close', function (close) {
heartbeat.reset() // 关闭心跳机制!!!
console.log('close=', close)
})
ws.on('message', function (message) {
let messageJson = JSON.parse(message)
ws.send(JSON.stringify(content)) // 接收到信息后循环发送信息
ws.close() // 关闭连接
})
let heartbeat = {
pingInterval: null,
reset () {
if (heartbeat.pingInterval !== null || heartbeat.pingInterval !== undefined) {
clearInterval(heartbeat.pingInterval)
}
},
start () {
heartbeat.pingInterval = setInterval(() => {
if (ws.readyState === 1) {
// ws.send('ping') // 网上都是这种写法,大家注意,可以去node_modules看下ws安装包README.md,我之前写这种各种不得行,后来才发现人家示例是下面那样得!
ws.ping()
}
}, 30000) // 每隔30s发送一次WebSocket ping帧以重置超时并检查连接是否仍然有效
}
}
}