Since the socket.io framework has components for both the server and the client, we will use these components to code our communication on both the sides. Events emitted on a socket on one side will be handled by the corresponding event handler on the other side. Socket.io is built so that both the sides can send messages or attach handlers to process the incoming messages.
Let's begin by understanding how the messages will flow. It is important to remember that "messages" here are not the actual messages sent and received by users of the chat system, but the messages used for communication by the client and the server. There will be two types of messages, as follows:
serverMessage
.myMessage
and userMessage
respectively.When a user connects for the first time, the server will send a welcome message to the user as a serverMessage
message.
When a user types in a message and presses the Send button, we will send a userMessage
message from the browser to the server.
On receiving the user message, the server will broadcast this message to all the other users. It will also send back the same message as myMessage
to the user who originally sent the message.
On receiving any message from the server, the browser will display the contents of the message in the message area.