组件:
import { websocketIp } from '../../config'
let ws = null
// 连接socket
function openWebsocket() {
ws = new WebSocket(websocketIp) // ws://192.168.10.65:58890/webSocket
ws.onopen = () => {
if (ws.readyState === 1) {
ws.send(
JSON.stringify({
// 连接成功将,用户ID传给服务端
uid: JSON.parse(sessionStorage.getItem('userInfo')).id
})
)
}
}
ws.onerror = err => {
console.log('websocket error:', err)
alert('websocket连接失败,建议退出重新登录')
}
return ws
}
export function getSocket1() {
return new Promise((resolve, reject) => {
if (!ws || ws.readyState !== 1) {
openWebsocket()
}
resolve(ws)
})
}
// 断开socket
export function closeSocket1() {
if (ws) {
ws.close()
ws.onclose = function () {
console.log('Socket关闭了')
}
}
}
export function getCarHireMsg1(fun) {
return getSocket1().then((socket) => {
socket.onmessage = msgEvent => {
console.log(msgEvent)
fun(msgEvent)
}
})
}
页面引用:
import { getCarHireMsg } from '@/socket/index'
created () {
getCarHireMsg(this.getSock)
}
// 连接socket
getSock(data) {
if (data.data !== '服务器连接成功!') {
this.handleWebSocket(data.data)
}
},
// 处理socket 信息
handleWebSocket(content) {
console.log(JSON.parse(content))
}
进阶版:包含心跳机制
https://blog.csdn.net/u013361179/article/details/115506472?spm=1001.2014.3001.5501
本文介绍了一个使用WebSocket进行实时通信的应用实例,包括如何建立连接、发送用户ID到服务器及接收服务器消息的处理方法。此外还提供了包含心跳机制的进阶版实现链接。

4637

被折叠的 条评论
为什么被折叠?



