websocket.js
1.42 KB
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
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-02-24 13:35:26
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-02-24 13:49:11
* @FilePath: \vue-2.6\src\platforms\web\util\websocket.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
function initWebSocket(e) {
console.log(e)
const wsUri = 'ws://192.168.3.191:7864/ws/1'
this.socket = new WebSocket(wsUri) //这里面的this都指向vue
//连接成功
this.websock.onopen = websocketonopen
this.socket.onerror = webSocketOnError
this.socket.onmessage = webSocketOnMessage
this.socket.onclose = closeWebsocket
}
function webSocketOnError(e) {
console.log('WebSocket连接发生错误')
}
function webSocketOnMessage(e) {
const data = JSON.parse(e.data)
console.log(data)
}
function websocketonopen() {
//连接成功事件
websocketsend('发送数据')
//提示成功
console.log('连接成功', 3)
//开启心跳
this.start()
}
// 关闭websiocket
function closeWebsocket() {
console.log('连接已关闭...')
}
function close() {
this.socket.close() // 关闭 websocket
this.socket.onclose = function (e) {
console.log(e) //监听关闭事件
console.log('关闭')
}
}
function webSocketSend(agentData) {
this.socket.send(agentData)
}
export default {
initWebSocket,
close
}