A Java-based multi-client chat application built using socket programming, object-oriented principles (OOP), and multi-threading. The server handles multiple clients simultaneously, allowing users to communicate in a group chat environment with unique usernames.
- ServerSocket listens for incoming client connections on a specified port (
12345). - Socket establishes a two-way communication channel between the server and clients.
- BufferedReader and PrintWriter handle text-based I/O streams for sending and receiving messages.
- Connection Lifecycle:
- Server waits for clients (
serverSocket.accept()). - Clients connect (
new Socket("localhost", 12345)). - Messages are exchanged via input/output streams.
- Clean disconnection using
/quitcommand.
- Server waits for clients (
- Encapsulation:
- The
ClientHandlerclass encapsulates client-specific logic (username, I/O streams). - Private fields with controlled access (e.g.,
socket,username).
- The
- Separation of Concerns:
Serverclass manages connections and broadcasting.Clientclass handles user input and server responses.
- Reusability:
- The
ClientHandlerthread can be reused for each new client connection.
- The
- Server-Side Threading:
- Each client runs in a separate
ClientHandlerthread. - The main thread continues listening for new connections.
- Each client runs in a separate
- Client-Side Threading:
- Receiving Thread: Continuously listens for incoming messages.
- Sending Thread: Handles user input and message transmission.
- Thread Safety:
synchronizedSetensures safe access to the connected clients list.synchronizedblocks prevent race conditions during broadcasts.
- Multi-client support (handles many users at once)
- Username-based identification (no anonymous messaging)
- Real-time group chat (messages broadcast to all)
- Graceful disconnections (
/quitcommand) - Join/leave notifications (automatic alerts)
- Starts and waits for clients (
ServerSocket.accept()). - For each new client:
- Creates a
ClientHandlerthread. - Prompts for a username.
- Adds client to the active connections list.
- Creates a
- Broadcasts messages to all clients (except sender).
- Removes disconnected clients and notifies others.
- Connects to the server (
Socket("localhost", 12345)). - Enters a username (sent to the server).
- Runs two threads:
- Receiver: Listens for messages from the server.
- Sender: Reads user input and sends messages.
- Disconnects cleanly with
/quit.
chat-app/
├── Client/
│ └── Client.java # Manages client-side connection & messaging
├── Server/
│ └── Server.java # Main server logic
├── build.bat
├── runClient.bat
├── runServer.bat
└── README.md
This project demonstrates socket programming for network communication, OOP for clean architecture, and multi-threading for handling concurrent clients. It serves as a foundation for building more advanced chat systems with additional features.