Skip to content

Instantly share code, notes, and snippets.

@ibtesam123
Created May 11, 2020 07:04
Show Gist options
  • Save ibtesam123/06adc28ec20c0e33f572cb0134f356ef to your computer and use it in GitHub Desktop.
Save ibtesam123/06adc28ec20c0e33f572cb0134f356ef to your computer and use it in GitHub Desktop.
Realtime Chat-II
const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http);
app.get('/', (req, res) => {
res.send("Node Server is running. Yay!!")
})
io.on('connection', socket => {
//Get the chatID of the user and join in a room of the same chatID
chatID = socket.handshake.query.chatID
socket.join(chatID)
//Leave the room if the user closes the socket
socket.on('disconnect', () => {
socket.leave(chatID)
})
//Send message to only a particular user
socket.on('send_message', message => {
receiverChatID = message.receiverChatID
senderChatID = message.senderChatID
content = message.content
//Send message to only that particular room
socket.in(receiverChatID).emit('receive_message', {
'content': content,
'senderChatID': senderChatID,
'receiverChatID':receiverChatID,
})
})
});
http.listen(process.env.PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment