I am using ws package in server side and I want the client to create/join rooms in server socket. And how to remove them from the a created room when they are no longer connected. PS: I don't want to use socketIo.
Creating a websocket serverPORT || 5001; middleware(app); api(app); const server = app. listen(port, () => { if (process. send) { process. send(`Server running at http://localhost:${port}\n\n`); } }); websockets(server); process.
In you above code you have fixed room to abc123 , that you need to make it dynamic for all connected clients . You can provide room create option to user also you can provide logic to change/rename/leave/join room from client. Basically in your client and server you can apply below logical changes.
You could try something like:
const rooms = {};
wss.on("connection", socket => {
const uuid = ...; // create here a uuid for this connection
const leave = room => {
// not present: do nothing
if(! rooms[room][uuid]) return;
// if the one exiting is the last one, destroy the room
if(Object.keys(rooms[room]).length === 1) delete rooms[room];
// otherwise simply leave the room
else delete rooms[room][uuid];
};
socket.on("message", data => {
const { message, meta, room } = data;
if(meta === "join") {
if(! rooms[room]) rooms[room] = {}; // create the room
if(! rooms[room][uuid]) rooms[room][uuid] = socket; // join the room
}
else if(meta === "leave") {
leave(room);
}
else if(! meta) {
// send the message to all in the room
Object.entries(rooms[room]).forEach(([, sock]) => sock.send({ message }));
}
});
socket.on("close", () => {
// for each room, remove the closed socket
Object.keys(rooms).forEach(room => leave(room));
});
});
This is only a sketch: you need to handle leave room, disconnection from client (leave all rooms) and delete room when nobody is longer in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With