Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create/join chat room using ws (Websocket) package in node js

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.

like image 223
Mbula Mboma Jean gilbert Avatar asked Jun 14 '20 09:06

Mbula Mboma Jean gilbert


People also ask

How do I create a node JS WebSocket server?

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.

How do you make a dynamic room in socket IO?

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.


1 Answers

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.

like image 70
Daniele Ricci Avatar answered Sep 28 '22 02:09

Daniele Ricci