我正在用socket.io创建一个快速反应项目。我的问题是,我已经阅读了文档,并且可以发出自定义事件。当然,数据没有问题,但是当我调试时,连接的用户在控制台中是垃圾邮件,示例数据也是如此。这是发生的事情的行为
我的代码:
服务器
const app = require("express")();
const server = require("http").Server(app);
const io = require("socket.io")(server);
const fs = require("fs");
// Our localhost port
const port = 5000;
server.listen(port, () => console.log(`Server listening on port ${port}`));
function emitData() {
fs.readFile('name.json','utf8', function(error, data) {
if (error) throw error;
console.log(JSON.stringify(data));
io.emit('complete data', JSON.stringify(data));
});
}
io.on("connection", socket => {
console.log("User connected");
emitData();
socket.on("timeout", data => {
console.log(data);
});
socket.on("disconnect", () => {
console.log("user disconnected");
});
});
React Client(在render()函数中)
const socket = socketIOClient(this.state.endpoint);
// socket.on is another method that checks for incoming events from the server
socket.on("complete data", data => {
this.setState({updatedData : data});
console.log(JSON.parse(data));
});
预先感谢