The third challenge awaits! If you want to jump to my implementation directly, here’s the GitHub link.
Problem Requirements:
Build a TCP server that can handle at least 10 simultaneous clients.
When a user sends a connection request, respond with a custom welcome message.
Example : Welcome to budget-chat! what do we call you?
The user responds to the welcome message with a name, which must be valid.
A valid name must:
contain at least 1 character.
consist entirely of alphanumeric characters (uppercase, lowercase, and digits).
Note that:
The server may or may not allow users to pick duplicate names (my solution does not).
A user is said to have “joined” the chat room after he has selected a valid name.
Once a new user joins, notify all other online users. Send a list of online users to the newly joined user.
Messages sent by a user must be broadcasted to all other users.
When a user leaves the chat room, notify all other online users.
Refer to the problem link for message formats.
Solution:
Let’s start by defining the BudgetChat struct.
Now lets accept multiple client connections simultaneously.
Before we implement the “handleClient” function for BudgetChat, lets define some constants for the message formats.
Now, lets define the “handleClient” function:
There’s a bunch of functionality to implement, lets start with setting the user’s name, provided its valid.
Now we define 2 helper functions, broadcastData (broadcasts bytes to all clients except the source of the data) and sendData(sends data to a specific client only).
We use these 2 helper functions extensively to do the following:
Broadcast messages sent by a user:
Broadcast a notification to other users informing them that a new user has joined the chat room, and send a list of online users to the newly joined user:
Broadcast a message to other online users when a user leaves the chat room.
The monster falters and falls, its reign has ended. For now, victory is ours!