【问题标题】:Socket.io is not connecting with client (react.js)Socket.io 未与客户端连接(react.js)
【发布时间】:2022-06-13 09:03:51
【问题描述】:

我正在尝试将我的 socket.io 服务器与客户端连接,但我没有收到任何关于它是否已连接的消息。 我在前端使用 React.js,在后端使用 node.js、express.js 和 MongoDB。

我不明白是服务器代码有问题还是客户端有问题。 请帮忙:")

socketServer/index.js

const io = require("socket.io")(6000, {
  cors: {
    origin: "http://localhost:3000",
  },
});

io.on("connection", (socket) => {
    console.log("user has been connected");
})

socketServer/package.json

{
  "name": "socketServer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "nodemon": "^2.0.16",
    "socket.io": "^4.5.1"
  }
}

client/Messenger.jsx

import React, { useContext, useEffect, useRef, useState } from 'react'

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

export default function Messenger() {
    const [socket, setSocket] = useState(null);
    useEffect(() => {
        setSocket(io("ws://localhost:6000"));
        console.log("tadan tadan", socket);
    }, [])
 return (
        <>
          this is messenger
        </>
    )
}

【问题讨论】:

    标签: node.js reactjs socket.io


    【解决方案1】:

    我认为您的客户端和服务器端都有错误。

    对于cors.origin,请尝试存储'*'。看起来您正在尝试构建一个实时聊天应用程序,因此您的套接字服务器必须侦听新消息。所以你可以重写你的套接字服务器如下:

    const server = require("http").createServer();
    const io = require("socket.io")(server, {
      cors: {
        origin: "*",
      },
    });
    
    const PORT = 4000;
    const NEW_CHAT_MESSAGE_EVENT = "newChatMessage";
    
    io.on("connection", (socket) => {
      
      // Join a conversation
      const { roomId } = socket.handshake.query;
      socket.join(roomId);
    
      // Listen for new messages
      socket.on(NEW_CHAT_MESSAGE_EVENT, (data) => {
        io.in(roomId).emit(NEW_CHAT_MESSAGE_EVENT, data);
      });
    
      // Leave the room if the user closes the socket
      socket.on("disconnect", () => {
        socket.leave(roomId);
      });
    });
    
    server.listen(PORT, () => {
      console.log(`Listening on port ${PORT}`);
    });
    
    

    链接here 的文章帮助我为我的应用构建了实时消息传递功能,以及我从何处获得上述代码。

    为了将客户端连接到套接字服务器并从服务器接收消息,我建议创建一个自定义挂钩来监听传入的消息。这是上面链接的文章中自定义挂钩的示例:

    import { useEffect, useRef, useState } from "react";
    import socketIOClient from "socket.io-client";
    
    const NEW_CHAT_MESSAGE_EVENT = "newChatMessage"; // Name of the event
    const SOCKET_SERVER_URL = "http://localhost:4000";
    
    const useChat = (roomId) => {
      const [messages, setMessages] = useState([]); // Sent and received messages
      const socketRef = useRef();
    
      useEffect(() => {
        
        // Creates a WebSocket connection
        socketRef.current = socketIOClient(SOCKET_SERVER_URL, {
          query: { roomId },
        });
        
        // Listens for incoming messages
        socketRef.current.on(NEW_CHAT_MESSAGE_EVENT, (message) => {
          const incomingMessage = {
            ...message,
            ownedByCurrentUser: message.senderId === socketRef.current.id,
          };
          setMessages((messages) => [...messages, incomingMessage]);
        });
        
        // Destroys the socket reference
        // when the connection is closed
        return () => {
          socketRef.current.disconnect();
        };
      }, [roomId]);
    
      // Sends a message to the server that
      // forwards it to all users in the same room
      const sendMessage = (messageBody) => {
        socketRef.current.emit(NEW_CHAT_MESSAGE_EVENT, {
          body: messageBody,
          senderId: socketRef.current.id,
        });
      };
    
      return { messages, sendMessage };
    };
    
    export default useChat;
    
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多