# **websocket**
## **后端**
#### **依赖**
```
npm install ws --save
```
#### **代码示例**
创建websocket文件夹,创建test.js测试文件
```
//创建一个WebSocket服务器,在10000端口启动
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 10000, path: "/ws" });
server.on("connection", (ws) => {
console.log("Client connected");// 链接成功
ws.on("message", (message) => {
console.log(`Received message: ${message}`);//接收前端发来的消息
});
let data = 0;
setInterval(() => {
if (data == 100) {
data = 0;
}
ws.send(`The current time is ${new Date().toLocaleTimeString()}`);//给前端发送消息
data++;
}, 1000);
ws.on("close", () => {
console.log("Client disconnected");// 监听关闭后回调
});
});
```
#### **使用**
在bin/www里面插入`require("../websockets/test");`代码,调用websocket
## **前端**
#### **代码实例**
```
<template>
<div>
<span>{{ dataMessage }}</span>
<input type="text" v-model="message" />
<div v-if="socket?.readyState === OPEN">
<el-button type="primary" size="default" @click="sendMessage">
发送
</el-button>
<el-button size="default" @click="closeSocket">关闭</el-button>
</div>
<div v-else>
<el-button size="default" @click="connection">链接</el-button>
</div>
</div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { ref, onUnmounted, onMounted } from "vue";
const OPEN = WebSocket.OPEN;
const socket = ref(null);
const dataMessage = ref("");
const message = ref("");
const sendMessage = () => {
socket.value.send(message.value);
};
const closeSocket = () => {
socket.value.close();
socket.value = null;
dataMessage.value = "";
ElMessage.success("连接已关闭");
};
const connection = () => {
socket.value = new WebSocket("/socket/ws");
socket.value.onopen = () => {
ElMessage.success("连接成功");
};
socket.value.onmessage = (event) => {
// console.log(event.data);
dataMessage.value = event.data;
};
};
onMounted(() => {
connection();
});
onUnmounted(() => {
closeSocket();
});
</script>
<style lang="scss" scoped></style>
```