【问题标题】:Socket IO namespace not working with Express套接字 IO 命名空间不适用于 Express
【发布时间】:2020-03-05 18:38:28
【问题描述】:

我已经尝试在后端设置命名空间,

const server = require("http").createServer(app);
const connectedUsers = {};

const io = require("socket.io")(server, {
  path: "/socket",
  serveClient: false,
  // below are engine.IO options
  pingInterval: 10000,
  pingTimeout: 5000,
  cookie: false
});

const singularConnection = io.of("/singular-socket");

singularConnection.on("connection", socket => {
    console.log("unique user connected with socket ID " + socket);
}

在我的客户端上,我尝试连接,

    const socket = io(GATEWAY, {
      path: "/socket/singular-socket",
      transports: ["websocket"],
      jsonp: false
    });

    socket.connect();

    socket.on("connect", () => {
      console.log("connected to socket server");
    });

我尝试了不同的 URL 变体,去掉了 /socket 并移动了其他东西,但我似乎无法让它工作。我在这里做错了什么?

【问题讨论】:

    标签: javascript node.js express socket.io


    【解决方案1】:

    我没有任何使用 socket.io 的经验,但是来自文档...

    要连接到命名空间,客户端代码应如下所示。

    const socket = io('http://localhost/admin', {
      path: '/mypath'
    });
    

    这里,套接字连接到 admin 命名空间,使用自定义路径 我的路径

    请求 URL 如下所示: localhost/mypath/?EIO=3&transport=polling&sid=(命名空间是 作为负载的一部分发送)。

    按照以上几行,您的代码应该看起来像..

     const socket = io("http://localhost/singular-socket", {
          path: "/socket",
          transports: ["websocket"],
          jsonp: false
        })
    

    其中/singular-socket 是命名空间,/socket 是路径。

    试试这个repl

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2014-01-24
      相关资源
      最近更新 更多