Vue and node use websocket to implement data push and real-time chat

Requirements: Node is used as the backend to connect to the database based on websocket. After the fields of the database are changed, the frontend can update the data without refreshing the page, and the frontend can also send messages to the backend. exhibit

1. Initialize node, generate package.json and package-lock.js

     npm init -y

2. Install express, socket.io, cors

npm install express socket.io cors -S

3. Create app.js and write code

Run the project with 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 // 允许发送凭据(如 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 3000');
});

4. The front end uses socket.io-client

npm install socket.io-client

Introduce in the page that needs to use websocket connection

<template>
    <div class="content-box">
        <div class="container">
          {
   
   { data }}
           <el-button @click="gasong">发送</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. Effect

The default is as follows:

The id is 243 and the database is changed to 245. The front end does not need to refresh the page, and the data is directly changed.

After clicking send, the backend receives the message, and then pushes the message to the frontend

 

 This is the end of the article, I hope it will be helpful to you~

 

Guess you like

Origin blog.csdn.net/qq_44278289/article/details/131395924