65 lines
1.3 KiB
JavaScript
65 lines
1.3 KiB
JavaScript
|
import { useUserStore } from '@/store/user'
|
||
|
|
||
|
export default function useWebSocket() {
|
||
|
const userStore = useUserStore()
|
||
|
|
||
|
let ws = null
|
||
|
|
||
|
const connectWebSocket = () => {
|
||
|
if (!userStore.isLogined) {
|
||
|
console.error("用户未登录,无法建立 WebSocket 连接")
|
||
|
return
|
||
|
}
|
||
|
|
||
|
const token = userStore.userInfo.token
|
||
|
const wsUrl = `${import.meta.env.VITE_WS_BASEURL}/chat/${token}` // 根据你的服务端口和路径
|
||
|
|
||
|
if (ws) {
|
||
|
console.log("WebSocket 已连接")
|
||
|
return
|
||
|
}
|
||
|
|
||
|
ws = new WebSocket(wsUrl)
|
||
|
|
||
|
ws.onopen = () => {
|
||
|
console.log("WebSocket 连接成功")
|
||
|
}
|
||
|
|
||
|
ws.onmessage = (event) => {
|
||
|
const message = event.data
|
||
|
console.log("收到消息:", message)
|
||
|
// 这里可以根据需要处理收到的消息,比如显示在聊天窗口
|
||
|
}
|
||
|
|
||
|
ws.onerror = (error) => {
|
||
|
console.error("WebSocket 错误:", error)
|
||
|
}
|
||
|
|
||
|
ws.onclose = () => {
|
||
|
console.log("WebSocket 连接关闭")
|
||
|
ws = null
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const sendMessage = (message) => {
|
||
|
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||
|
console.error("WebSocket 尚未连接,无法发送消息")
|
||
|
return
|
||
|
}
|
||
|
ws.send(message)
|
||
|
}
|
||
|
|
||
|
const closeWebSocket = () => {
|
||
|
if (ws) {
|
||
|
ws.close()
|
||
|
ws = null
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return {
|
||
|
connectWebSocket,
|
||
|
sendMessage,
|
||
|
closeWebSocket,
|
||
|
}
|
||
|
}
|