Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

creating room in ws nodejs

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));
  });
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: js addeventlistener input searcb mobile 
Javascript :: array destructuring by using spread operator from a nested object in javascript 
Javascript :: expressjs allow cors for all hosts and ports 
Javascript :: javascript string to boolean 
Javascript :: how to disable input in javascript 
Javascript :: react rating stars component 
Javascript :: json validator 
Javascript :: vue js data property in component must be a function 
Javascript :: Delete a user in ExpressJS 
Javascript :: slice string javascript 
Javascript :: shopify api for add to cart 
Javascript :: Regex for number divisible by 5 
Javascript :: node check text include in file 
Javascript :: servicenow gliderecord lookup 
Javascript :: upload multiple image using jquery 
Javascript :: how to check popup is open or not in javascript 
Javascript :: hook use effect with hooks 
Javascript :: chess.js 
Javascript :: react native shadow maker 
Javascript :: universal mobile number regex 
Javascript :: parse string javascript 
Javascript :: classic asp json multidemsion json 
Javascript :: sum up all the first and last digit of a number until only two digits are left 
Javascript :: what is shortest javascript program 
Javascript :: console 
Javascript :: javascript url 
Javascript :: app script append two list 
Javascript :: javascript reduce function array 
Javascript :: node js code for saving first middle and last name 
Javascript :: tagged templates 
ADD CONTENT
Topic
Content
Source link
Name
6+1 =