websocket 方法类
import { defineStore } from "pinia";
interface WebSocketStoreState {
ws: WebSocket | null;
callbacks: ((message: string) => void)[];
connected: boolean;
}
export const useWebSocketStore = defineStore("webSocket", {
state: (): WebSocketStoreState => ({
ws: null,
callbacks: [],
connected: false,
}),
actions: {
connect(url: string): void {
if (this.ws) {
console.warn("WebSocket already connected");
return;
}
this.ws = new WebSocket(url);
this.ws.onopen = () => {
console.log("WebSocket connected");
this.connected = true;
};
this.ws.onmessage = (event: MessageEvent) => {
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);
},
reconnect(url: string): void {
if (url) {
console.log("Reconnecting WebSocket...");
this.ws = new WebSocket(url);
this.ws.onopen = () => {
console.log("WebSocket connected");
this.connected = true;
};
this.ws.onmessage = (event: MessageEvent) => {
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");
}
},
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() {
const webSocketStore = useWebSocketStore();
const connectWebSocket = () => {
const url = "ws://localhost:3030";
debugger;
if (!webSocketStore.connected) {
webSocketStore.connect(url);
}
};
const sendMessage = () => {
const message = "Hello, WebSocket!";
webSocketStore.send(message);
};
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,
};
},
});
</script>
websocket 服务端 测试实例
1.项目中安装 websocket 模块
npm install ws
2.添加如下服务代码
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
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));
});
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