gpt4 book ai didi

javascript - Socket IO 命名空间不适用于 Express

转载 作者:行者123 更新时间:2023-12-02 22:34:41 25 4
gpt4 key购买 nike

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

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 并移动了其他内容,但我似乎无法让它工作。我在这里做错了什么?

最佳答案

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

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

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

Here, the socket connects to the admin namespace, with the custom path mypath.

The request URLs will look like: localhost/mypath/?EIO=3&transport=polling&sid= (the namespace is sent as part of the payload).

按照上述几行,您的代码应该如下所示..

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

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

试试这个 repl

关于javascript - Socket IO 命名空间不适用于 Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58778255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com