node.js - 与 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.
我怎样才能让它运行?
解决方案
刚刚迁移到 websockets,这些没有任何抱怨
推荐阅读
- typescript - 定义一个类型,它是一个以另一个类型定义的键开头的字符串?
- mongodb - yii2 mongodb - 如何在集合子数组中查找元素
- calendar - 修改日历中的事件以成为重复事件
- php - 在php中将单词排列在数组中
- c# - 在 NET Standard 项目中使用 .NET 4.6.1 NuGet 包时出现问题(bin 中缺少 dll)
- react-navigation - react-navigation tabBarComponent 无法读取未定义的属性“键”
- ffmpeg - ffmpeg 检测立体声通道是否实际上是单声道
- javascript - 循环更改 SVG 填充
- bixby - “不总是返回格式化值”错误怎么办?
- c# - 如何在打印机上打印测试页?