WebSocket 封装
WebSocket是一种网络传输协议,可在单个TCP连接上进行全双工通信,位于OSI模型的应用层。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就可以创建持久性的连接,并进行双向数据传输。
WebSocket协议规范将ws(WebSocket)和wss(WebSocket Secure)定义为两个新的统一资源标识符(URI)方案,分别对应明文和加密连接。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
| let websock = null
let messageCallback = null // callback message important !!!!
let errorCallback = null
let wsUrl = ''
// 接收ws后端返回的数据
function websocketonmessage (e) {
messageCallback(JSON.parse(e.data))
}
/**
* 发起websocket连接
* @param {Object} agentData 需要向后台传递的参数数据
*/
function websocketSend (agentData) {
// 加延迟是为了尽量让ws连接状态变为OPEN
setTimeout(() => {
// 添加状态判断,当为OPEN时,发送消息
if (websock.readyState === websock.OPEN) { // websock.OPEN = 1
// 发给后端的数据需要字符串化
websock.send(JSON.stringify(agentData))
}
if (websock.readyState === websock.CLOSED) { // websock.CLOSED = 3
console.log('websock.readyState=3')
console.error('ws连接异常,请稍候重试')
errorCallback()
}
}, 500)
}
// 关闭ws连接
function websocketclose (e) {
// e.code === 1000 表示正常关闭。 无论为何目的而创建, 该链接都已成功完成任务。
// e.code !== 1000 表示非正常关闭。
if (e && e.code !== 1000) {
console.error('ws连接异常,请稍候重试')
errorCallback()
}
}
// 建立ws连接
function websocketOpen (e) {
// console.log('ws连接成功')
}
// 初始化weosocket
function initWebSocket () {
if (typeof (WebSocket) === 'undefined') {
console.error('您的浏览器不支持WebSocket,无法获取数据')
return false
}
const token = 'JWT=' + getToken()
// ws请求完整地址
const requstWsUrl = wsUrl + '?' + token
websock = new WebSocket(requstWsUrl)
websock.onmessage = function (e) {
websocketonmessage(e) // callback message important !!!!!!!
}
websock.onopen = function () {
websocketOpen()
}
websock.onerror = function () {
console.error('ws连接异常,请稍候重试')
errorCallback()
}
websock.onclose = function (e) {
websocketclose(e)
}
}
/**
* 发起websocket请求函数
* @param {string} url ws连接地址
* @param {Object} agentData 传给后台的参数
* @param {function} successCallback 接收到ws数据,对数据进行处理的回调函数
* @param {function} errCallback ws连接错误的回调函数
*/
export function sendWebsocket (url, agentData, successCallback, errCallback) {
wsUrl = url
initWebSocket()
messageCallback = successCallback // callback message important !!!!!!!
errorCallback = errCallback
websocketSend(agentData)
}
/**
* close websocket function
*/
export function closeWebsocket () {
if (websock) {
websock.close()
websock.onclose()
}
}
|
参考:
封装websocket请求—–vue项目实战
回调函数