[英]Socket.io failing to emit functions
I've been working on a game with socket.io and found out that socket.emit function doesn't seem to work properly when second argument is a function. When I use socket.on and try to call (or even console.log) the function, it says data.testFunction is not a function. I've also tried using objects, but when received, all object methods are missing.我一直在玩 socket.io 的游戏,发现当第二个参数是 function 时,socket.emit function 似乎无法正常工作。当我使用 socket.on 并尝试调用(甚至是 console.log)时function,它说 data.testFunction 不是 function。我也尝试过使用对象,但是当收到时,所有 object 方法都丢失了。
node.js code: node.js 代码:
const
http = require("http"),
fs = require("fs"),
port = 9009;
const server = http.createServer((req, res) => {
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(fs.readFileSync("client/index.html", "utf8"));
res.end();
}
server.listen(port);
const io = require("socket.io")(server, {});
io.sockets.on("connection", (socket) => {
console.log("socket connection");
socket.emit("test", () => {return 2+2;});
}
And index.html:和 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet">
<style>
*{
margin: 0;
overflow: hidden;
background: #333;
font-family: "Poppins", sans-serif;
}
canvas{
background: #777;
}
</style>
</head>
<body>
<script src="https://cdn.socket.io/socket.io-3.0.0.js"></script>
<script>
const socket = io();
socket.on("test", (func) => {
func();
console.log(func);
});
</script>
</body>
</html>
What i get:我得到什么:
Uncaught ReferenceError: func is not defined
undefined
Passing function as string将 function 作为字符串传递
socket.emit("test", (() => {return 2+2;}).toString());
Calling function stored as string调用存储为字符串的 function
socket.on("test", (func) => {
eval(func)();
console.log(func);
});
test测试
const fun = (() => {return 2+2;}).toString() console.log(typeof fun) console.log(eval(fun)())
I think you need to specific URL for io()我认为您需要为 io() 指定 URL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.