gpt4 book ai didi

node.js - Socket.io : sending to all clients in a namespace,(不包括发件人)

转载 作者:行者123 更新时间:2023-12-03 11:59:08 24 4
gpt4 key购买 nike

我已经从socket.io官方网站上看到了这个socket.io cheatsheet,并且在堆栈溢出时在这里得到了一些答案。我没有找到想要的答案。

我如何发送给命名空间中的所有客户端(发件人除外)?

最佳答案

如果套接字连接到 namespace ,则可以使用socket.broadcast.emit转发消息

const app = require("express")();
const http = require("http").createServer(app);
const PORT = 3000;
const io = require("socket.io")(http);

app.get("/", (req, res) => {
res.send("<h1>This is a socket io server</h1>");
});

http.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});

io.of("/").on("connection", function(socket) {
});

io.of("chat").on("connection", function(socket) {
socket.on("message", data => {
// socket is connected to namespace so just broadcast the emit to other clients in the namespace
socket.broadcast.emit("message", {
user: socket.id,
message: data.message
});
});
});

关于node.js - Socket.io : sending to all clients in a namespace,(不包括发件人),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60769547/

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