【问题标题】:Reconnecting to socket channel after disconnection in react在反应中断开连接后重新连接到套接字通道
【发布时间】:2021-11-26 05:21:34
【问题描述】:

这个问题有多种答案,但要么已经过时(我认为“重新连接”事件不再存在?),要么对我不起作用。

我有大量数据,客户端通过 socket.io 套接字从服务器等待。直到 10-15 分钟后,超过 1600 个结果套接字重新连接都可以。重新连接发生后,我不再获得服务器发出的数据,我认为这是因为我丢失了原始套接字连接的事件。

我必须刷新才能继续获取该数据。

如何在每次重新连接后重新连接到 socket.io?

客户:

socket.js(上下文)

import { createContext } from 'react';
import io from 'socket.io-client';

export const socket = io('http://localhost:5000');

export const SocketContext = createContext();

布局.js

import { socket, SocketContext } from '../context/socket'

function MyApp({ Component, pageProps }) {

  return <SocketContext.Provider value={socket}>
    <Layout>
      <Component {...pageProps} />
    </Layout>
  </SocketContext.Provider>
}

页面(next.js)

  import { SocketContext } from '../context/socket'; 
  ...
  const socket = useContext(SocketContext);
  useEffect(() => {
    socket.emit('joined', socketChannel);
    socket.on(socketChannel, handleStream);
  }, []);

服务器:

index.js(使用fastify-socket.io

    fastify.io.on('connection', socket => {
        socket.on('joined', (channel) => {
            socket.join(channel);
        })
    });
    redis.subscriber.on('message', (channel, message) => {
        io.to(channel).emit(channel, message);
    });

【问题讨论】:

  • 默认情况下会自动重新连接。您使用forceNew: true 有什么原因吗?好像您正在管理 React Context 中的连接,您可以分享该代码吗?
  • 我试图从另一个答案管理连接,但没有成功,我会更新并修复代码。
  • 你能分享createContext()代码吗,我假设这使用React.Context
  • @SamuelGoldenbaum 我已经做过了,我想我说得不够清楚,更新了问题。
  • 好的,我想我发现了问题

标签: javascript reactjs socket.io next.js fastify


【解决方案1】:

当您断开连接时,Socket.io 会自动离开房间。

房间断开后会自动离开。

useEffect(),您将加入房间一次:

  socket.emit('joined', socketChannel);
  socket.on(socketChannel, handleStream);

两种选择:

  1. 在客户端连接时自动加入:
  useEffect(() => {
    socket.on(socketChannel, handleStream);

    // connect fires when connected, also after reconnected
    socket.on('connect', () => {
      console.log('connect', socket.connected);
      // automatically join the room
      socket.emit('joined', socketChannel);
    });
  }, []);
  1. 在服务器上自动加入,但这假设所有客户端都加入了可能不适合的相关房间:
io.on('connection', (socket) => {
  console.log(`${socket.id} connected`);

  // automatically join the room
  socket.join(socketChannel);
  ...

【讨论】:

  • 您好,我尝试在离开房间时发出断开连接事件,但它没有被触发useEffect(() =&gt; { socket.on("connect", () =&gt; { socket.emit("join-room", { username: context.user.first_name + Math.random(), roomname: id, }); }); return () =&gt; socket.on("discon"); }, []);
猜你喜欢
  • 1970-01-01
  • 2019-03-05
  • 1970-01-01
  • 2021-12-09
  • 2012-08-07
  • 2016-03-08
  • 1970-01-01
  • 2019-02-22
  • 2016-02-06
相关资源
最近更新 更多