需求:node做后端根据websocket,连接数据库,数据库的字段改变后,前端不用刷新页面也能更新到数据,前端也可以发送消息给后端,后端接受后把前端消息做处理再推送给前端展示
1.初始化node,生成package.json和package-lock.js
npm init -y
2.安装express、socket.io、cors
3.创建app.js并编写代码
使用node ./websocket.js运行项目
npm install express socket.io cors -S
建立websocket.js
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const fs = require('fs');
const cors = require('cors');
// 使用 cors 中间件允许跨域请求
// 配置跨域选项
const corsOptions = {
origin: '*', // 指定允许的来源
methods: ['GET', 'POST'], // 允许的请求方法
credentials: true // 允许发送凭据(如 cookies)
};
app.use(cors(corsOptions));
// 创建数据库连接
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',//数据库连接域名
user: 'root',//数据库账号
password: '123456',//密码
database: 'graduation_design'//要连接的数据库名
});
connection.connect();
// 监听客户端连接事件
io.on('connection', (socket) => {
console.log('A client connected');
//查询表
connection.query('SELECT * FROM shelves', (error, results) => {
if (error) throw error;
//数据推送到前端
socket.emit('data', results);
},)
// 发送数据到客户端
setInterval(() => {
// 查询数据库并发送数据到客户端
connection.query('SELECT * FROM shelves', (error, results) => {
if (error) throw error;
socket.emit('data', results);
},)
}, 60 * 1000);
//接收到客户端的消息后再推送给客户端
socket.on('message', (message) => {
console.log('接收到客户端消息:', message);
socket.emit("messagedata", message);
})
// 监听客户端断开连接事件
socket.on('disconnect', () => {
console.log('A client disconnected');
});
});
// 启动服务器
http.listen(3000, () => {
console.log('WebSocket server is running on port 3333');
});
4.前端使用socket.io-client
npm install socket.io-client
在需要使用websocket连接的页面引入
<template>
<div class="content-box">
<div class="container">
{{ data }}
<el-button @click="connectWebscoket">连接websocket</el-button>
<el-button @click="gasong">发送</el-button>
<el-button @click="stop">停止连接</el-button>
<hr />
{{ msgdata }}
</div>
</div>
</template>
<script>
import io from 'socket.io-client'
let socket = null
export default {
data() {
return {
data: null,
msgdata: ''
}
},
mounted() {},
methods: {
connectWebscoket() {
// 解决跨域问题
socket = io('http://localhost:3333', {
transports: ['websocket'],
withCredentials: true, //白名单
extraHeaders: {
//请求头
'Access-Control-Allow-Origin': 'http://localhost:8080'
}
})
socket.on('data', (data) => {
this.data = data
})
socket.on('messagedata', (msg) => {
this.msgdata = msg
})
},
gasong() {
socket.send('Hello from client!')
},
stop() {
socket.close()
}
}
}
</script>
<style lang="scss" scoped></style>
此时已经建立好websocket的连接