Handling events

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:

  • The system messages: These messages will be sent by our chat system to the client, like when the user is connected, when others connect, or when users disconnect. Let's identify it with serverMessage.
  • The user messages: These messages will be sent by the client to the server and will actually carry the user's message content in the payload. We will probably want to differentiate between the messages we send and the messages other users send. So let's call them 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset