Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
 just start learn WebSocket and made chat with Node js. But if user disconnect i dont know how delete him in page(so that other users can see that he has left). I

This my localhost on Node.js, I think need delete user from array users but it dont work.

JavaScript
<pre>let server=require('ws').Server;
let s=new server({port:'9001'})
let users=[]


s.on('connection',(x)=>{
    x.on('message',(mess)=>
    { let inputMess=JSON.parse(mess);
        
       x.send(JSON.stringify(users))
        
        if(inputMess.type==='users'){
           users.push(inputMess.text);
           s.clients.forEach(client=>{
            client.send(JSON.stringify({type:'users', text:inputMess.text}))
        
        })
        }
        else if(inputMess.type==='del'){
           console.log(inputMess.user)
        }
        else if(inputMess.type==='message'){
         s.clients.forEach((client)=>{
            
            if(client!==x){
                let data=JSON.stringify({type:'message',user:inputMess.user,text:inputMess.text});
                client.send(data)
            }
         })
        }
        
    })  
    x.on('close', ()=>{console.log('User exit')})
       
            
    console.log("New user")
         
        })
and this is client

JavaScript
<pre> let sendButton=document.querySelector('button')
        let input=document.querySelector("input")
        let socket=new WebSocket('ws://localhost:9001')
        let span=document.querySelector('span')
        let inputLog=document.querySelector("#names")
        let subLog=document.querySelector('#sendlog')
        let chat=document.querySelector('.conteiner')
        let spisok=document.querySelector('ul')
        

        let currentName;
     
        let flag=false;
        console.log(socket);
        console.log(users)

        subLog.addEventListener('click',function(){
           currentName=inputLog.value
              
            let mess=JSON.stringify({type:'users',text:currentName})
            socket.send(mess)
            index++;
            console.log(users)
            
            inputLog.value=""
            inputLog.setAttribute('readonly','readonly')
            subLog.setAttribute("disabled", "disabled");
        })
        sendButton.addEventListener('click',function(){
            let mess=JSON.stringify({type:'message',user:currentName,text:input.value});
            
            chat.insertAdjacentHTML('beforeend',`<div class='mess'>Ти:${input.value}</div>`)
            socket.send(mess)
            input.value=""
        })
       
        
         socket.onmessage= (event) => {
                 let mess=JSON.parse(event.data);
                 console.log('You have 1 new message!', mess); 

                 if(mess.type==='users' ){
                    let li=document.createElement('li');
                    li.textContent=mess.text;
                    spisok.append(li)
                 } 
                 else if(mess.type ==='message'){
                 
                    chat.insertAdjacentHTML('beforeend',`<div class='mess'>${mess.user}:${mess.text}</div>`)
                    
                 }  
                 else if(mess.type === 'delete'){
                    console.log(mess.user) 
                 } 
                  else{
                 if(!flag){
                     
                     for(i=0;i<mess.length;i++){
                        let id=mess[i]
                        if(currentName!=id){ 
                       
                        console.log(mess[i])
             let li=document.createElement('li');
                    li.textContent=mess[i];
                    spisok.append(li) 
                        }}}}
                        flag=true}
                socket.onclose=(event)=>{
                     let us=JSON.stringify({type:'del',user:currentName})
                      socket.send(us)
                    console.log(event) 
                }



What I have tried:

Actually i dont know how do this
Posted
Updated 5-Jan-23 8:19am

1 solution

To delete users from a chat room in a web application using WebSockets and Node.js, you will need to implement a mechanism for removing the user's connection from the list of active connections.

Here is an example of how you could do this using the ws library for WebSockets in Node.js:

JavaScript
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

// Array to store the list of active connections
const connections = [];

wss.on('connection', (ws) => {
  // Add the new connection to the list
  connections.push(ws);

  ws.on('close', () => {
    // Remove the connection from the list when it closes
    connections = connections.filter((conn) => conn !== ws);
  });
});

In this example, the connections array is used to store the list of active connections. When a new connection is established, it is added to the array using the push method. When a connection closes, it is removed from the array using the filter method.

You can then use the connections array to broadcast messages or perform other actions on the chat room's users. For example, you could use the forEach method to iterate over the connections and send a message to each one:
JavaScript
connections.forEach((conn) => {
  conn.send('Hello, everyone!');
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900