Socket Chat

0 views
Skip to first unread message

Kristy Suzuki

unread,
Aug 3, 2024, 1:28:30 PM8/3/24
to riepaburtio

I am working on an Angularjs and Node.js based application. This is an organization based application. In this app, I have to implement chat functionality. So as we all know Socket.io is the best solution for instant messaging app and its reliability. But apart from this, I have few doubts regarding Socket.io. As of my understanding when we use socket programming (Socket.io in my case), for each and every connection it reserves a port. What if the size of an organization is too big? Will it work? At the server side, I am using Express js. Will Socket.io creates extra load on the server?

HTTP polling for any sort of interactive timing is enormously inefficient. You will have tens of thousands of clients repeatedly asking your server, "do you have anything new for me?" and the server regularly responding "no, nothing yet".

Modern servers can be configured to handle hundreds of thousands of simultaneous webSocket connections. How many a single server of yours can actually handle in the real life working of your application depends upon dozens of factors, none of which you've disclosed in your question. But, selecting webSocket/socket.io is not a bad architectural choice for two-way chat - that's the kind of application is was invented for because it's generally better than HTTP polling at that sort of thing.

For beginners, chat using socket.io is really simple to understand and integrate. However, the amount of bandwidth will depend heavily on the amount of data you're going to send from the server, and how much data the client will send. The bandwidth usage will also depend on which Socket.IO transport you're using, and the heartbeat interval of your application.

The performance impact of the application also varies on the type of application you're running and the performance capability of your machine and/or network. However, 5000+ clients will have a considerable impact on performance, regardless of your computer's capabilities unless you are scaling the application across multiple cores.

Go with Socket.io. It is incredibly relevant today for highly interactive applications like chat module. With web socket, there is no negotiation protocols and connection remain open as long as users concerned are registering for service with the web server. The payload is significantly less than http/https protocol.

We have all encountered chat over the web, that can be Facebook, Instagram, Whatsapp and the list goes on.
Just to give a bit of context, you send a message to a person or a group, they see the message and reply back. Simple yet complex.

To develop a chat app you would need to be aware of new messages as soon as they arrive.
Usually, to get information from the server you need send an HTTP request. With websockets, the server lets you know when there is new information without asking it.

In this article, we'll leverage the real-time communication provided by Socket.io to create an open chat application that allows users to send and receive messages from several users on the application. You will also learn how to detect the users who are online and when a user is typing.

Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between web browsers and a Node.js server. It is a highly performant and reliable library optimized to process a large volume of data with minimal delay. It follows the WebSocket protocol and provides better functionalities, such as fallback to HTTP long-polling or automatic reconnection, which enables us to build efficient chat and real-time applications.

In this section, we'll set up the project environment for our chat application. You'll also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.

From the code snippet above, the socket.io("connection") function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.

? For the remaining part of this article, I will walk you through creating the web pages for the chat application and sending messages back and forth between the React app and the Node.js server. I'll also guide you on how to add the auto-scroll feature when a new message arrives and how to fetch active users in your chat application.

The code snippet assigns different routes for the Home and Chat page of the application using React Router v6 and passes the Socket.io library into the components. We'll create the Chat page in the upcoming section.

From the image above, the Chat page is divided into three sections, the Chat Bar - sidebar showing active users, the Chat Body containing the sent messages and the header, and the Chat Footer - the message box and the send button.

In this section, you'll learn how to send messages from the React app to the Node.js server and vice-versa via Socket.io. To send the messages to the server, we will need to pass the Socket.io library into the ChatFooter - component that sends the messages.

The handleSendMessage function checks if the text field is empty and if the username exists in the local storage (sign-in from the Home page) before sending the message event containing the user input, username, the message ID generated, and the socket or client ID to the Node.js server.

From the code snippet above, Socket.io listens to the messages sent via the messageResponse event and spreads the data into the messages array. The array of messages is passed into the ChatBody component for display on the UI.

socket.on("newUser") is triggered when a new user joins the chat application. The user's details (socket ID and username) are saved into the users array and sent back to the React app in a new event named newUserResponse.
In socket.io("disconnect"), the users array is updated when a user leaves the chat application, and the newUserReponse event is triggered to send the updated the list of users to the client.

From the code snippets above, lastMessageRef is attached to a div tag at the bottom of the messages, and its useEffect has a single dependency, which is the messages array. So, when the messages changes, the useEffect for the lastMessageRef re-renders.

From the code snippet above, the handleTyping function triggers the typing event whenever a user is typing into the text field. Then, we can listen to the typing event on the server and send a response containing the data to other users via another event called typingResponse.

Feel free to improve the application by adding the Socket.io private messaging feature that allows users to create private chat rooms and direct messaging, using an authentication library for user authorization and authentication and a real-time database for storage.

Socket.io is a great tool with excellent features that enables us to build efficient real-time applications like sports betting websites, auction and forex trading applications, and of course, chat applications by creating lasting connections between web browsers and a Node.js server.

The way socket.io actually works is by assuming those are AJAX requests and once some communications had been exchanged it switches the protocol, thus it's not a protocol downgrade but an upgrade (you can check that in the network tab of chrome dev tools), also check the link in the last comment for more details. Is it convenient?

Also note that socket.io has 4 different versions and both client and server need to implement the same version as far as I can remember, hence as soon as v5 appears you'll need to provide both v4 and v5 versions to avoid current clients software breaking and to provide latest stable version for new customers or customers that want to migrate (thinking on the use-case of providing just a backend as service).

It's true and not true, it's like saying that compare to the population of the world, you child will be chinese, it's most likely not true :)
So while it's true that if you target the whole world with your app that might be the case.
But try to do the same for old enterprise companies, and I promise you, you will find some Windows XP :D

I'd rather prefer the connection to be tested with the "newest" protocol and downgrade it if there's any incompatibility instead doing the opposite. It will add a delay to people with very very old devices and software and speed up the rest.

My logic is that people with very very old devices and software are already used to the slowness ?I know it by experience, had a Pentium II with a 56Kb modem for more than 10 years, on those waiting times 100-200ms won't harm much, it's a little % overall ?

Because you mentioned about browser notification, I searched in MDN if there was a tools for that purpose. So I mean like this one : developer.mozilla.org/en-US/docs/W...
Of course, you are free to use other tools, library you have found suitable for that purpose.

Nice, I am waiting for that.
Actually, I also want to see how you handle global state management if there are cases for that. Specifically, how you use Redux, because I am learning Redux with the recommended way mentioned in the Redux doc, i.e using Redux Toolkit (RTK) and RTK Query.
But it is just fine if you don't use it in that app.

In my last project, I didn't use it, because I didn't learn it, it would take longer time before I could really use it. For global state management, I used a lib named reactN by Charles Stover which was easy to use.
But now that I realize in what case Redux is suitable for, I think I am going to use it for my nearest project.

Hi, novu team.
This is so great.
I also checked your packages on github, 7.3k stars - so amzing.
Btw I want to know about nove.co platform's pricing.
This is free platform? I signed on platform but there's no payment setup.

It offers a real-time collaborative code editor featuring unique room generation, syntax highlighting, and auto-suggestions. Users can seamlessly edit, save, and download files while communicating through group chat

c80f0f1006
Reply all
Reply to author
Forward
0 new messages