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!