首页 > 解决方案 > 与 React 一起使用时,Socket.io 不响应事件

问题描述

我正在尝试将我的 CRA 前端连接到用 Node.js 制作的 Socket.io websocket 服务器,但它似乎不起作用。下面是 Socket 服务器的配置:

const app = require("express")();
const server = require("http").createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

io.on("connection", function (socket) {
  console.log("A user connected.");

  socket.on("set video", function (url) {
    console.info("> Set the video to '" + url + "'");
    socket.broadcast.emit("set video", { url });
  });
});

server.listen(3001, function () {
  console.info("WS is listening on port 3001.");
});

这是 React 组件:

type Props = {
  readonly method: Dispatch<SetStateAction<string>>;
};

const VideoProvider = () => {
  const [source, setSource] = useState<string>("");

  const handleSubmit = (event: FormEvent) => {
    event.preventDefault();
    const ws = io("http://127.0.0.1:3001");
    ws.on("connect", function () {
      ws.emit("set video", { url: source });
    });
  };

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    setSource(event.target.value);
  };

  return (
    <fieldset style={{ width: "400px" }}>
      <legend>Set video URL</legend>

      <form onSubmit={handleSubmit}>
        <label htmlFor="video">Enter video's URL</label>{" "}
        <input
          id="video"
          type="url"
          placeholder="Enter video's URL (.mp4)"
          value={source}
          onChange={handleChange}
          required
        />{" "}
        <input type="submit" />
      </form>
    </fieldset>
  );
};

运行 Socket 服务器时,它返回监听函数的回调,仅此而已:

Server is listening on port 3001.

我怎样才能让它运行?

标签: node.jsreactjssocket.io

解决方案


刚刚迁移到 websockets,这些没有任何抱怨


推荐阅读