1

I have recently started learning about Node js and developed a Realtime chat application where whoever is connected to the server they can have a chat but now I want to add a feature of private chat between two users only so how can I achieve it? I have read about the room functionality of socket.io but by that I can get that it's a room and in that room there can be many users and they can have chat but it's not personal means many users can join the same chat. I need to know how to implement chat feature where two people can have a chat no third person can enter that particular chat. My question is different than other questions present here as I want to implement both the functionalities I need group and private chat both in one application. My idea is in my group chat functionality username and message are displayed so if one user clicks on username then the person can start their personal private chat no third person can join it.

Here I am sharing my code snippets for your reference

Server.js

  const io = require('socket.io')(http)

io.on('connection', (socket) => {
    console.log('Connected...')
    socket.on('message', (msg) => {
        socket.broadcast.emit('message', msg)
    })

})

Client.js

   const socket = io()
let name;
let textarea = document.querySelector('#textarea')
let messageArea = document.querySelector('.message__area')
do {
    name = prompt('Please enter your name: ')
} while(!name)

textarea.addEventListener('keyup', (e) => {
    if(e.key === 'Enter') {
        sendMessage(e.target.value)
    }
})

function sendMessage(message) {
    let msg = {
        user: name,
        message: message.trim()
    }
    // Append 
    appendMessage(msg, 'outgoing')
    textarea.value = ''
    scrollToBottom()

    // Send to server 
    socket.emit('message', msg)

}

function appendMessage(msg, type) {
    let mainDiv = document.createElement('div')
    let className = type
    mainDiv.classList.add(className, 'message')

    let markup = `
        <h4>${msg.user}</h4>
        <p>${msg.message}</p>
    `
    mainDiv.innerHTML = markup
    messageArea.appendChild(mainDiv)
}

// Recieve messages 
socket.on('message', (msg) => {
    appendMessage(msg, 'incoming')
    scrollToBottom()
})

function scrollToBottom() {
    messageArea.scrollTop = messageArea.scrollHeight
}

Please help me out!

prateek_pro
  • 67
  • 3
  • 10

1 Answers1

0

when a new user join keep that socket id, and while sending message send that unique userid and emit message to that socket only,

    const io = require('socket.io')(http)
    var user={};
    io.on('connection', (socket) => {

        console.log('Connected...')
        
        socket.on('join', (userid) => {
            users[userid]=socket.id;
        });

        socket.on('privateMessage', (data) => {
            io.sockets.socket(users[data.to]).emit('message', data.msg);
        });

        socket.on('publicMessage', (msg) => {
            socket.broadcast.emit('message', msg)
        });
    });
Tony
  • 894
  • 4
  • 19
  • I want both the functionality in my application means group chat is currently working now I need private chat so in my front end there is button for private chat then I want that on clicking that button user may get list of connected people then he selects with whom he want to talk privately then private chat begins – prateek_pro Nov 12 '20 at 05:21
  • you have to create room for group chat. `socket.broadcast.emit('message', msg)` will send message to all users except the sender..for private message you can use the code i mentioned above – Tony Nov 12 '20 at 05:26
  • for private message send userid, since we are keeping socket id based on key value pair and userid as key we can send message directly to that socket. – Tony Nov 12 '20 at 05:35
  • Okay can you be little brief in code. I think it's better way to have private message by this approach like in my group chat the name of user is displaying with the message and when user clicks on that name then they both should be in private chat mode. – prateek_pro Nov 12 '20 at 05:40