socket.io没有与客户端连接(react.js)

发布于 2025-02-05 14:32:46 字数 1189 浏览 3 评论 0原文

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

我不明白服务器代码还是客户端中是否有故障。 请帮助:“)

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
        </>
    )
}

I am trying to connect my socket.io server with the client, but I am not getting any message that it is connected or not.
I am using React.js for the front-end and node.js, express.js, and MongoDB for backend.

I don't understand whether there is a fault in the server code or in the client.
please help :")

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
        </>
    )
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨曦慕雪 2025-02-12 14:32:47

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

对于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}`);
});

链接的文章在这里帮助我为应用程序和获得以上代码的位置构建了我的实时消息传递功能。

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

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;

希望有所帮助。

I think there are errors in both your client-side and your server side.

For cors.origin try storing a '*'. Looks like you are trying to build a real-time chat app, thus your socket server has to listen for new messages. So you can rewrite your socket server as follows:

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}`);
});

The article linked here helped me build my real time messaging feature for my app and where I got the above code.

For connecting the client to the socket-server and receiving messages from the server, I would suggest creating a custom hook that will listen for incoming messages. Here's the example of the custom hook from the article linked above:

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;

Hope this helped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文