How to realize instant messaging + disconnection and reconnection through websoket?

This blog is just a demo, and the specific application should be combined with the actual situation of the project. The following is the directory structure:

1. First build a local server through express

npm install express

2. Customize test data in serve.js 

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.send('服务器搭好了');
});

app.get('/list', (req, res) => {
  res.send([
    { id: 1, name: 'Tom', age: 18 },
    { id: 2, name: 'Jerry', age: 12 },
    { id: 3, name: 'houseHolder', age: 30 }
  ]);
});

// 0.0.0.0 表示监听当前机器所有ip 包含本机ip和外网ip
server.listen(2000, '0.0.0.0', () => {
  console.log('127.0.0.1:2000');
});

3. Run the server

node serve.js

Note: how to check all ip? (local + extranet ip)

npm install http-server

Enter directly in the terminal: http-server

4. Test whether the server is turned on

Send the request, you can get the returned data, and the server is successfully started

 5. Realize the client code through socket.io-client

npm install socket.io-client

6. Create a websocket server

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

+const { Server } = require("socket.io");
+// 创建了一个websocket服务器,并解决了跨域的问题
+const io = new Server(server, { cors: true });

+// 监听与客户端的连接事件
+io.on('connection', socket => {
  console.log('服务端连接成功');
  // 监听浏览器传过来的事件
  socket.on('handle', (e) => {
    console.log(e, 'app传过来的数据');
    socket.emit('message', e);
  })
})

app.get('/', (req, res) => {
  res.send('服务器搭好了');
});

app.get('/list', (req, res) => {
  res.send([
    { id: 1, name: 'Tom', age: 18 },
    { id: 2, name: 'Jerry', age: 12 },
    { id: 3, name: 'houseHolder', age: 30 }
  ]);
});

// npm install -g http-server查看所有ip  0.0.0.0 表示监听当前机器所有ip 包含本机ip和外网ip
server.listen(2000, '0.0.0.0', () => {
  console.log('127.0.0.1:2000');
});

 7. Import socket.io's cdn online package in app/index.js and connect to the local server

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.socket.io/4.4.0/socket.io.min.js"></script>
</head>

<body>
  <input type="text" id="ipt" placeholder="请输入内容">
  <button id="btn">按钮</button>

  <script>
    let socket = io('ws://192.168.18.162:2000')
    // 监听浏览器、服务器是否建立连接
    socket.on('connect', () => {
      console.log('浏览器和服务器连接上了');
    })

    socket.on('message', (e) => {
      console.log(e, '服务器传过来的值');
    })

    const btn = document.querySelector('#btn')
    const ipt = document.querySelector('#ipt')
    btn.addEventListener('click', () => {
      console.log(ipt.value, 'input框信息');
      // 向服务器传递表单数据
      socket.emit('handle', ipt.value);
    })
  </script>
</body>

</html>

8. Both the client and the server can get the value of the input box after the connection is successful

 

 9. Optimization: Solve the problem of disconnection and reconnection

Idea: In the function of monitoring whether the connection with the server is successful, the client monitors the disconnection function, and if the connection fails, set the timer to re-establish the connection every 3s

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.socket.io/4.4.0/socket.io.min.js"></script>
</head>

<body>
  <input type="text" id="ipt" placeholder="请输入内容">
  <button id="btn">按钮</button>

  <script>
    let socket = io('ws://192.168.18.162:2000')
    // 监听浏览器、服务器是否建立连接
    socket.on('connect', () => {
      console.log('浏览器和服务器连接上了');

      // 解决:断线重连
      console.dir(socket)
      socket.on('disconnect', () => {
        let intervalSocket = null
        intervalSocket = setInterval(() => {
          console.log("disconnect:" + socket.disconnected)
          if (socket.disconnected) {
            socket = io('ws://192.168.18.162:2000')
          } else {
            clearInterval(intervalSocket)
          }
        }, 3000)
      })

    })

    socket.on('message', (e) => {
      console.log(e, '服务器传过来的值');
    })

    const btn = document.querySelector('#btn')
    const ipt = document.querySelector('#ipt')
    btn.addEventListener('click', () => {
      console.log(ipt.value, 'input框信息');
      // 向服务器传递表单数据
      socket.emit('handle', ipt.value);
    })
  </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/weixin_48082900/article/details/129392700