websocket 服务 pinia 全局配置
websocket 方法类
// stores/webSocketStore.ts
import { defineStore } from "pinia";
interface WebSocketStoreState {
ws: WebSocket | null; // WebSocket 实例
callbacks: ((message: string) => void)[]; // 消息回调函数列表
connected: boolean; // 连接状态
}
export const useWebSocketStore = defineStore("webSocket", {
state: (): WebSocketStoreState => ({
ws: null,
callbacks: [],
connected: false,
}),
actions: {
// 连接 WebSocket
connect(url: string): void {
if (this.ws) {
console.warn("WebSocket already connected");
return;
}
// 创建 WebSocket 实例
this.ws = new WebSocket(url);
// 监听连接打开事件
this.ws.onopen = () => {
console.log("WebSocket connected");
this.connected = true;
};
// 监听消息事件
this.ws.onmessage = (event: MessageEvent) => {
// console.log("Received message:", event.data);
this.callbacks.forEach((callback) => callback(event.data)); // 执行回调
};
// 监听错误事件
this.ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
// 监听连接关闭事件
this.ws.onclose = () => {
console.log("WebSocket connection closed");
this.connected = false;
};
},
// 发送消息
send(message: string): void {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(message);
} else {
console.error("WebSocket is not open");
}
},
// 注册接收消息的回调函数
onMessage(callback: (message: string) => void): void {
this.callbacks.push(callback);
},
// 重新连接 WebSocket
reconnect(url: string): void {
if (url) {
console.log("Reconnecting WebSocket...");
// 创建 WebSocket 实例
this.ws = new WebSocket(url);
// 监听连接打开事件
this.ws.onopen = () => {
console.log("WebSocket connected");
this.connected = true;
};
// 监听消息事件
this.ws.onmessage = (event: MessageEvent) => {
// console.log("Received message:", event.data);
this.callbacks.forEach((callback) => callback(event.data)); // 执行回调
};
// 监听错误事件
this.ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
// 监听连接关闭事件
this.ws.onclose = () => {
console.log("WebSocket connection closed");
this.connected = false;
};
} else {
console.error("No URL available to reconnect");
}
},
// 关闭 WebSocket 连接
close(): void {
if (this.ws) {
this.ws.close();
}
},
},
});
页面中使用例子
<template>
<div>
<el-button @click="connectWebSocket">Connect WebSocket</el-button>
<el-button @click="sendMessage">Send Message</el-button>
<el-button @click="closeWebSocket">Close WebSocket</el-button>
<el-button @click="reconnect('ws://localhost:3030')"
>Reset Connection</el-button
>
<div v-if="webSocketStore.connected">WebSocket is connected</div>
<div v-else>WebSocket is disconnected</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { useWebSocketStore } from "@/store/webSocketStore"; // 根据实际路径调整
export default defineComponent({
setup() {
// 获取 Pinia store
const webSocketStore = useWebSocketStore();
// 连接 WebSocket
const connectWebSocket = () => {
const url = "ws://localhost:3030"; // 替换为实际的 WebSocket URL
debugger;
if (!webSocketStore.connected) {
webSocketStore.connect(url);
}
// if (webSocketStore.ws?.readyState != 1) {
// webSocketStore.ws?.onopen;
// }
};
// 发送消息
const sendMessage = () => {
const message = "Hello, WebSocket!";
webSocketStore.send(message);
};
// 关闭 WebSocket
const closeWebSocket = () => {
webSocketStore.close();
};
const reconnect = (url: string) => {
webSocketStore.reconnect(url);
};
// 注册接收到消息的回调函数
webSocketStore.onMessage((message) => {
console.log("Received message in component:", message);
});
return {
connectWebSocket,
sendMessage,
closeWebSocket,
reconnect,
webSocketStore,
connected: webSocketStore.connected, // 从 store 中获取连接状态
};
},
});
</script>
websocket 服务端 测试实例
1.项目中安装 websocket 模块
npm install ws
2.添加如下服务代码
// 导入必要的模块
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
// 创建一个 Express 应用
const app = express();
// 创建一个 HTTP 服务器
const server = http.createServer(app);
// 创建 WebSocket 服务器,传入 HTTP 服务器对象
const wss = new WebSocket.Server({ server });
// WebSocket 连接事件处理
wss.on('connection', (ws) => {
console.log('A new client connected.');
// 监听客户端发送的消息
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
// 发送消息回客户端
ws.send(`${message}`);
});
// 连接关闭时的处理
ws.on('close', () => {
console.log('Client disconnected.');
});
const jsonData = {
SendName: "server",
ReceiveName: "connectionning client",
SendDataInfo: { msg: "welcome connection success", type: "tips" },
};
const plainData = { ...jsonData };
// 发送欢迎消息给客户端
ws.send(JSON.stringify(plainData));
});
// 设置一个基本的 HTTP 路由
app.get('/', (req, res) => {
res.send('Hello, Node.js with WebSocket!');
});
// 设置端口并启动服务器
const PORT = process.env.PORT || 3030;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
3. 启动websocket 测试服务端
node server.js
原文地址:https://blog.csdn.net/qq_42899641/article/details/144429266
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!