需求:node做后端根據(jù)websocket,連接數(shù)據(jù)庫,數(shù)據(jù)庫的字段改變后,前端不用刷新頁面也能更新到數(shù)據(jù),前端也可以發(fā)送消息給后端,后端接受后把前端消息做處理再推送給前端展示
1.初始化node,生成package.json和package-lock.js
? ? ?npm init -y
2.安裝express、socket.io、cors
npm install express socket.io cors -S
3.創(chuàng)建app.js并編寫代碼
使用node ./app.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 // 允許發(fā)送憑據(jù)(如 cookies)
};
app.use(cors(corsOptions));
// 創(chuàng)建數(shù)據(jù)庫連接
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',//數(shù)據(jù)庫連接域名
user: 'root',//數(shù)據(jù)庫賬號
password: '123456',//密碼
database: 'graduation_design'//要連接的數(shù)據(jù)庫名
});
connection.connect();
// 監(jiān)聽客戶端連接事件
io.on('connection', (socket) => {
console.log('A client connected');
//查詢表
connection.query('SELECT * FROM shelves', (error, results) => {
if (error) throw error;
//數(shù)據(jù)推送到前端
socket.emit('data', results);
},)
// 發(fā)送數(shù)據(jù)到客戶端
setInterval(() => {
// 查詢數(shù)據(jù)庫并發(fā)送數(shù)據(jù)到客戶端
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);
})
// 監(jiān)聽客戶端斷開連接事件
socket.on('disconnect', () => {
console.log('A client disconnected');
});
});
// 啟動服務器
http.listen(3000, () => {
console.log('WebSocket server is running on port 3000');
});
4.前端使用socket.io-client
npm install socket.io-client
在需要使用websocket連接的頁面引入
<template>
<div class="content-box">
<div class="container">
{{ data }}
<el-button @click="gasong">發(fā)送</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() {
// 解決跨域問題
socket = io('http://localhost:3000', {
transports: ['websocket'],
withCredentials: true,//白名單
extraHeaders: {//請求頭
'Access-Control-Allow-Origin': 'http://localhost:8081'
}
});
socket.on('data', data => {
this.data = data;
});
socket.on("messagedata",msg=>{
this.msgdata=msg;
})
},
methods: {
gasong(){
socket.send('Hello from client!');
}
}
};
</script>
<style lang="scss" scoped></style>
5.效果
默認如下:
id為243 在數(shù)據(jù)庫改為245前端不需要刷新頁面,數(shù)據(jù)直接改掉了
點擊發(fā)送后,后端收到消息,再把消息推送給前端
?文章來源:http://www.zghlxwxcb.cn/news/detail-605640.html
?文章到此結束,希望對你有所幫助~文章來源地址http://www.zghlxwxcb.cn/news/detail-605640.html
到了這里,關于vue和node使用websocket實現(xiàn)數(shù)據(jù)推送,實時聊天的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!