简体   繁体   中英

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.
node.js code:

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:

<!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

socket.emit("test", (() => {return 2+2;}).toString());

Calling function stored as string

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM