显示所有活动房间的列表socket.io

发布于 2025-01-10 04:37:00 字数 2003 浏览 1 评论 0原文

我是 socket.io 的初学者,我想知道我是否正在做正确的事情来显示创建的所有活动房间的列表。每次我尝试调用我的房间列表组件时,socket.io 的服务器端都会崩溃,所以我真的开始认为我在某个地方犯了错误。有没有更好/更简单的方法来做到这一点,或者我做的是正确的事情吗?

更新:我的服务器已停止崩溃,但我的 useEffect 没有收到来自 getActiveRooms() 的返回。另外我仍然想知道我是否真的必须创建一个房间来发出房间列表?

服务器端

const express = require('express');
const app = express();
const http = require('http');
const cors = require('cors'); 
const { Server } = require("socket.io");
app.use(cors());

const PORT = 3001;
const server = http.createServer(app);

const io = new Server(server, { 
    cors: {
        origin: 'http://localhost:3000',
        methods: ["GET", "POST"],
    }
});

function getActiveRooms(io) {
    // Convert map into 2D list:
    // ==> [['4ziBKG9XFS06NdtVAAAH', Set(1)], ['room1', Set(2)], ...]
    const arr = Array.from(io.sockets.adapter.rooms);
    // Filter rooms whose name exist in set:
    // ==> [['room1', Set(2)], ['room2', Set(2)]]
    const filtered = arr.filter(room => !room[1].has(room[0]))
    // Return only the room name: 
    // ==> ['room1', 'room2']
    const res = filtered.map(i => i[0]);
    console.log(`Liste des rooms actives : ${res}`)
    return res;
}

io.on("connection", (socket) => {
    socket.on("room_list", (data) => {
        socket.join(data); //data is a room called listroom that will receive all rooms (string)
        socket.to(data).emit("receive_room", getActiveRooms(io)); 
    });
});

server.listen(PORT, () => {
    console.log(`Serveur lancé sur le port ${PORT}`);
});

客户端(它是一个名为 ListeRoom 的组件)

function ListeRooms({socket, username}) {

    const classes = useStyles(); 
    const [roomList, setRoomList] = useState([]);
    
    useEffect(() => {
        socket.on("receive_room", (data) => {
            setRoomList((liste) => [...liste, data]); 
        })
    }, [socket]);

我的组件在主页中接收的参数

<ListeRooms socket={socket} username={username}/>

I'm a begginer with socket.io and I wanted to know if I am doing the right thing to display the list of all active rooms created. The server side of socket.io keep crashing everytime I am trying to call my room list component so I really start to think that I am making a mistake somewhere. Is there a better/easier way to do this or am I doing the right thing ?

UPDATE: My server has stopped crashing but my useEffect doesn't receive my return from getActiveRooms(). Also I'm still wondering if I really have to create a room to emit the room list?

Server Side

const express = require('express');
const app = express();
const http = require('http');
const cors = require('cors'); 
const { Server } = require("socket.io");
app.use(cors());

const PORT = 3001;
const server = http.createServer(app);

const io = new Server(server, { 
    cors: {
        origin: 'http://localhost:3000',
        methods: ["GET", "POST"],
    }
});

function getActiveRooms(io) {
    // Convert map into 2D list:
    // ==> [['4ziBKG9XFS06NdtVAAAH', Set(1)], ['room1', Set(2)], ...]
    const arr = Array.from(io.sockets.adapter.rooms);
    // Filter rooms whose name exist in set:
    // ==> [['room1', Set(2)], ['room2', Set(2)]]
    const filtered = arr.filter(room => !room[1].has(room[0]))
    // Return only the room name: 
    // ==> ['room1', 'room2']
    const res = filtered.map(i => i[0]);
    console.log(`Liste des rooms actives : ${res}`)
    return res;
}

io.on("connection", (socket) => {
    socket.on("room_list", (data) => {
        socket.join(data); //data is a room called listroom that will receive all rooms (string)
        socket.to(data).emit("receive_room", getActiveRooms(io)); 
    });
});

server.listen(PORT, () => {
    console.log(`Serveur lancé sur le port ${PORT}`);
});

Client Side (it's a component called ListeRoom)

function ListeRooms({socket, username}) {

    const classes = useStyles(); 
    const [roomList, setRoomList] = useState([]);
    
    useEffect(() => {
        socket.on("receive_room", (data) => {
            setRoomList((liste) => [...liste, data]); 
        })
    }, [socket]);

Parameter that my component receive in my main page

<ListeRooms socket={socket} username={username}/>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文