如何从外部react连接到nextjs的websocket



我正试图通过websocket从nextjs发送消息到一个单独的react应用程序,但新的websocket,不知道如何做到这一点,所以任何帮助将是感激的,我可以从我的nextjs客户端通过api发送消息到websocket,但我如何从另一个应用程序连接到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 })

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

相关内容

  • 没有找到相关文章

最新更新