如何从外部react连接到nextjs WebSocket

oxiaedzo  于 2023-04-20  发布在  React
关注(0)|答案(1)|浏览(99)

我试图通过WebSocket从nextjs发送消息到一个单独的react应用程序,但新的websockets,不知道如何做到这一点,所以任何帮助将不胜感激,我可以从我的nextjs客户端发送消息到websocket通过API,但我如何连接到websocket从另一个应用程序?有时会得到这个错误:http://localhost:3000/socket.io?EIO=4&transport=polling&t=OTv_Djk 404 Not Found
nextjs _app.tsx:

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

  const socket = io('http://localhost:3000', {
     path: '/api/socket'
  });

  useEffect(() => {
    socket.emit('createdMessage', 'message');
  }, []);

API/socket.ts:

export default function SocketHandler(_: NextApiRequest, res: NextApiResponseServerIO) {
  if (res.socket.server.io) {
    res.end();
    return;
  }

  const io = new Server(res.socket.server as any, {
    path: '/api/socket',
    cors: {
      origin: ['*']
    }
  });
  res.socket.server.io = io;

  const onConnection = (socket: any) => {
    messageHandler(io, socket);
  };

  io.on('connection', onConnection);
  res.end();
}

function messageHandler(_: any, socket: any) {
  const createdMessage = (msg: string) => {
    console.log('createdMessage', msg);
    socket.broadcast.emit('newIncomingMessage', msg);
  };

  socket.on('createdMessage', createdMessage);
}

使用CRA制作的单独应用程序(未连接到WebSocket):

const { lastMessage, readyState } = useReactWebSocket(
    'ws://localhost:3000',
    {
      retryOnError: false,
      reconnectAttempts: Number.MAX_SAFE_INTEGER,
      reconnectInterval: 5000,
      shouldReconnect: () => isMounted.current
    },
    true
  );

  console.log({ lastMessage, readyState })
igsr9ssn

igsr9ssn1#

我能让它工作的唯一方法是使用定制的nextjs服务器。

相关问题