1、初始化(确保当前电脑有node环境)
bash
npm init
2、安装express
bash
npm i express
bash
npm i ws
文件结构
3、编写相关代码启动node服务(server.js)
javascript
//导入下列模块,express搭建服务器,fs用来操作文件、ws用来实现webscoket
const express = require("express")
const path = require("path")
const app = express()
const fs = require("fs")
const txt = fs.readFileSync('./msg.text','utf-8')
console.log("文件运行成功",txt)
app.all('*', function (req, res, next) {
// 解决跨域
res.header('Access-Control-Allow-Origin', '*');
// 设置相应头数据
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
// 设置接收的方法
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
next();
});
//编写127.0.0.1:3333/index接口
//返回值为resObj
app.get("/index", (req, res) => {
console.log("请求携带的参数", req)
const resObj = {
code: "200",
msg: '成功了',
data: [1, 2, 3]
}
//obj填写到msg.text文件中
fs.writeFileSync('./msg.text',JSON.stringify(resObj ),'utf-8')
res.json(resObj )
})
const serve = app.listen(3333, () => {
console.log('服务启动成功');
})
//导入ws模块,实现双向通讯
const WebSocket = require('ws');
const clients = new Set();
// 创建 WebSocket 服务器
const wss = new WebSocket.Server({server:serve });
// 监听连接事件
wss.on('connection', (ws) => {
clients.add(ws);
// 监听消息事件
//以广播的形式发送消息
ws.on('message', (message) => {
clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
// 发送消息到客户端
client.send(message);
}
});
});
// 监听关闭事件
ws.on('close', () => {
console.log('Client disconnected');
});
});
4、启动服务
bash
node server.js
5、编写前端(客户端)代码
ws.js
javascript
const url = "ws://127.0.0.1:3333"
const ws = new WebSocket(url)
ws.onmessage = (e) => {
console.log('接受到信息___________________>>>>>>>>>', e);
}
ws.onerror = function (err) {
console.log(err)
}
ws.onclose = function (e) {
console.log("中断连接", e)
}
ws.onopen = function (e) {
console.log("打开连接", e)
}
export default ws
App.vue
html
<template>
<div>
<span @click="msgFn">点击发送消息</span>
</div>
</template>
<script setup>
import ws from './ws.js'
const msgFn=()=>{
ws.send({name:"tjq说xxxx"})
}
</script>
<style scoped></style>