Private chat using socket io

Article


author small image Siva Kishore G
Posted : 11 Dec 2021
Modified : 06 Jun 2022
Expert Developers

One-On-One private chat

In this tutorial, I will explain how to do a private one-on-one chat. Lot of tutorials out there explain how to do single user & client chat. But with this, you can create a multi one-to-one chat. Still confused? Let me give you an example;Imagine you are a company wanting to sell chat features to your clients.

Setup

For this, you will need to work on three ends viz: Server, Admin & client.

  1. NodeJS Server
    Install socket.io, initialize DB connection and start listening on any port you wish to use
  2. Admin Site
    Initialize socket io for client var socket = io("your-socket-io-server-url");
  3. Customer Site
    Initialize socket io for client var socket = io("your-socket-io-server-url");

Logic

Everytime a client connects to the socket, it is issued a new socket ID and this ID changes everything the user reloads the page. So, the logic here is to save the socket ID and associate it with some ID that doesn't change (or at least until the user clears browser data).

socket io private chat architecture

Consider every admin-client as a chat node. Each chat node has one admin and multiple clients and their own room IDs. Don't get confused about this room ID with Socket IO's rooms.

Do it yourselves

Pause here and try it yourselves since you get the logic. I strongly believe in self-learning... I mean, a teacher tells you how to do something but when you learn it yourselves, you will know how "NOT" to do it and eventually do it right!

OR

Continue ...


Let's get into it then!

Follow the below in same exact sequence

Client - Server

Upon connection, emit onClient event and pass room ID , username , admin username
  1. Listen to onClient and save all values into the database along with the socketid
  2. Now check the messages database for any messages already logged with the roomid (primary key) and emit chatMsgs privately using io.to(client_socket_id).emit("chatMsgs", chatMessages) event and pass messages object
Listen to chatMsgs and populate the chat box body with the messages received
Listen to adminOnline event to get admin socket which is supplied by the admin and save it in global variable or local storage
How? Keep reading, You will see the logic
Server will emit adminOnline event when the admin emits adminIsOnline and supply the socket id
To send message, emit clientResponse event and supply it message , admin socketid , roomid
Listen to clientResponse event, save the message in database , look for the socket id of the admin in the database and send the same message privately to that socket.
Listen to message event to get the message sent by the admin via chat server and update chat UI.
Tip : After recieving every message, auto scroll the chat body to that message

Admin - Server

Upon connection, emit onAdmin event and pass a security token (this is usually the JWT token received while login).
Listen to onAdmin event and get a token that was sent by the admin. This token should authorize the server to save the user details and socket. Query the database to get all users connected (previous & current). Emit chatUsers event and supply the users received
Listen to clientOnline to get the users that are online. This is where you need to update the local usesr variable and update UI
Examine the code below and get an idea on how to implement the user typing.
      var userTypingTimeout = null
socket.on('userIsTyping', data => {
  if (data === currentRoomId) {
  $('#userFeedback').show().text("User is typing ...")
  clearInterval(userTypingTimeout)
  userTypingTimeout = setTimeout(function() {
    $('#userFeedback').hide()
  }, 3000)
}})
    

Conclusion

I've left out some pieces of the tutorial deliberately. The idea is to show you a direction on how to attain private chat. Figure out things like User Disconnected, User reconnected, End chat etc. There are more refinements you can do such as initiate chat connection only when the user enters details such as name , email , phone etc.

Tip : Use some sort of heart beat to notify admins / clients to update their online status
Tip : Use socket IO's rooms to notify admins / client when someone joined or left

Thank you and feel free to comment your thoughts



Post a comment

I promise, I keep it clean *

Comments

Alert SVG Cookie Consent

This website uses cookies and similar technologies, to enhance your browsing experience and provide personalized recommendations. By continuing to use our website, you agree to our Privacy policy.