首先,这个只是给自己记录一下,防止以后用到的时候忘记,再次,因为这个时候后端不支持WebSocket请求,所以是否有bug还未可知,因此可以作为参考,但是不建议照抄,如果有哪位实验成功了别忘了私信我,咱们交流交流,共同进步
官网:WebSocket - Web API 接口参考 | MDN
直接贴代码:
封装的JS
import axios from 'axios'
export default class WebSocketClient {
constructor(url, apiEndpoint) {
this.url = url
this.apiEndpoint = apiEndpoint
this.socket = null
this.connected = false
this.messages = []
this.error = null
}
connect() {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
return
}
this.socket = new WebSocket(this.url)
this.socket.addEventListener('open', () => {
console.log('WebSocket connected')
this.connected = true
// 连接成功后发送 API 请求
this.sendApiRequest()
})
this.socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data)
this.messages.push(message)
})
this.socket.addEventListener('error', (event) => {
console.error('WebSocket error:', event)
this.error = event
})
this.socket.addEventListener('close', () => {
console.log('WebSocket closed')
this.connected = false
})
}
disconnect() {
if (this.socket) {
this.socket.close()
}
}
sendMessage(message) {
if (this.socket.readyState !== WebSocket.OPEN) {
return
}
this.socket.send(JSON.stringify(message))
}
sendApiRequest() {
axios.get(this.apiEndpoint).then(response => {
// 处理 API 返回数据并发送给服务端
const data = response.data
this.sendMessage(data)
}).catch(error => {
console.error('API request error:', error)
})
}
}
Vue
<template>
<div>
<ul>
<li v-for="message in messages" :key="message.id">{{ message.content }}</li>
</ul>
</div>
</template>
<script>
import WebSocketClient from './WebSocketClient.js'
export default {
name: 'WebSocket',
data() {
return {
messages: [],
error: null,
client: null
}
},
mounted() {
// 创建 WebSocketClient 实例并连接到服务端 API 接口,第一个是服务器地址,第二个是接口
this.client = new WebSocketClient('ws://192.168.0.107:8082/', 'http://example.com/api')
this.client.connect()
},
beforeUnmount() {
// 在组件销毁前断开 WebSocket 连接
this.client.disconnect()
}
}
</script>