如何从外部的React应用连接到Next.js的WebSocket。

huangapple go评论67阅读模式
英文:

How to connect to nextjs websocket from external react

问题

I am trying to send messages over a websocket from nextjs to a separate react app but new to websockets and not sure how to do it so any help would be appreciated, I can send a message from my nextjs client to the websocket via api but how do I connect to the websocket from another application? Sometimes get this error: 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);
}

separate app made with CRA (does not connect to 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 })
英文:

I am trying to send messages over a websocket from nextjs to a separate react app but new to websockets and not sure how to do it so any help would be appreciated, I can send a message from my nextjs client to the websocket via api but how do I connect to the websocket from another application? Sometimes get this error: 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);
}

separate app made with CRA (does not connect to 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 })

答案1

得分: 0

只有通过自定义的Next.js服务器,我才能让它正常工作。

英文:

Only way I could get it to work is with a custom nextjs server.

huangapple
  • 本文由 发表于 2023年4月13日 16:14:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定