【问题标题】:Socket.io not responding to events when used with React与 React 一起使用时,Socket.io 不响应事件
【发布时间】:2021-06-28 16:47:00
【问题描述】:

我正在尝试将我的 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.js reactjs socket.io


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2012-09-16
      相关资源
      最近更新 更多