首页 > 解决方案 > 与 nodejs-backend 和 react-app 的不稳定 websocket 连接

问题描述

我有一个 nodejs 服务器,上面有一个在 GCP VM 上运行的 socket.io 服务器。

socket.io@2.1.1
socket.io-redis@5.4.0

这是我的nodejs代码:

const express = require('express');
const app = express();
const http = require('http').createServer(app);
const redisClient = require('./redis');
const redisAdapter = require('socket.io-redis');

const io = require('socket.io')(http, {
  cors: {
    origin: '*'
  }
});

io.adapter(redisAdapter({ pubClient: redisClient.duplicate(), subClient: redisClient.duplicate() }));

io.on('connection', (socket) => {
  console.log('user connected', socket.id);
  // saving the socket ID related to the place ID in the redis database
  redisClient.set(`${socket.handshake.query.placeId}`, socket.id);
  socket.on('close', () => console.log('close'));
  socket.on('disconnect', () => {
    console.log('user disconnected', socket.id);
  })
});

我也有一个反应应用程序,在 App.js 中我连接到套接字服务器:

socket.io-client@2.2.0
react@17.0.2
react-dom@7.0.2

反应代码(简化):

useEffect(() => {
  if (auth && placeId) {
    initSocket();
  } else if (!auth && socket) {
    deleteSocket();
  }
}, [auth, placeId]);

const [socket, setSocket] = useState(null);

const initSocket = () => {
  let socket = io('wss://URL_TO_SERVER', {
    query: `placeId=${placeId}`
  });
  setSocket(socket);
  socket.on('connect', () => {
    dispatch({ type: 'SOCKET', payload: { connection: true } });
  });
  socket.on('order', (data) => {
    let order = JSON.parse(data);
    dispatch({ type: 'PUSH_ORDER', payload: { order } });
  });
  socket.on('disconnect', () => {
    dispatch({ type: 'SOCKET', payload: { connection: false } });
  });
};

const deleteSocket = () => {
  socket.close();
};

我将连接状态存储在应用程序的 redux 中,并且在我的应用程序布局中有一个小的“通知”图标在绿色(已连接)和红色(已断开)之间切换。

问题是:连接非常不稳定。有时我连接了一分钟,然后连接失败一瞬间,然后重新建立连接。有时我的通知图标甚至在绿色和红色之间闪烁。

在 chrome 中检查控制台时,出现以下错误:

Failed to load resource: the server responded with a status of 400 ()

这是我得到的另一个错误(有时):

WebSocket connection to 'wss://URL_TO_SERVER/socket.io/?placeId=1001&EIO=3&transport=websocket&sid=rGjmk2JObO_wUTdKAAAW' failed:

(在“失败:”之后没有打印任何内容)

使用此工具进行测试时,我无法连接到我的 websocket 服务器。使用 chrome 扩展进行测试时,我也无法连接到 websocket 服务器。

我知道我使用的是旧的 socket.io-client 版本(2.2.0),但是对于 4.1.3 版本,我没有任何连接。现在我得到了一个连接,但它一直失败并重新启动(然后工作了大约 1 分钟)。

它之所以有效,是因为建立连接后,我可以通过 websocket 服务器发送消息。

什么可能是错的?

标签: node.jsreactjssocket.io

解决方案


推荐阅读