A multi-client TCP chat server and client application written in Java. This project demonstrates a simple chat system where multiple clients can connect to a server, send messages, and receive broadcasts from other clients.
- Multi-client support: Server can handle multiple concurrent client connections
- Message broadcasting: Messages from one client are broadcasted to all connected clients
- Virtual threads: Uses Java 21 virtual threads for efficient client handling
- Graceful shutdown: Server stops accepting new clients after 30 seconds of inactivity
- Simple protocol: Custom message protocol with support for names, messages, and quit commands
- Java 21 or higher
- Gradle 9.1.0 or higher (included via wrapper)
To build the project, run:
./gradlew buildOn Windows:
gradlew.bat buildThe application can run as either a server or a client. When you run it, you'll be prompted to choose:
-
Start the application:
./gradlew run
-
Enter
0when prompted to start the server -
The server will start on port 5000 and wait for client connections
-
Server will stop accepting new clients after 30 seconds of inactivity
-
Start the application:
./gradlew run
-
Enter
1when prompted to start the client -
Enter your name when prompted
-
Once connected, you can:
- Type messages to send to all connected clients
- Type
/quitto disconnect from the server
To test multiple clients, open multiple terminal windows and run the client mode (1) in each window. All clients will see messages from each other.
- Server: Main server class that accepts client connections
- Dispatcher: Handles message routing and broadcasting to all connected clients
- ClientHandler: Manages individual client connections and message processing
- Client: Handles connection to server, sending messages, and receiving broadcasts
The application uses a simple text-based protocol:
n| <name>- Set client namem| <message>- Send a message to all clientsq|- Quit/Disconnect from serverc|- Command (reserved for future use)
tcp-app-java/
├── app/
│ ├── src/
│ │ ├── main/
│ │ │ └── java/
│ │ │ └── org/
│ │ │ └── example/
│ │ │ ├── App.java # Main entry point
│ │ │ ├── Server.java # Server implementation
│ │ │ ├── Client.java # Client implementation
│ │ │ └── SendType.java # Message type constants
│ │ └── test/
│ └── build.gradle.kts
├── gradle/
├── build.gradle.kts
└── README.md
To create an executable JAR:
./gradlew jarThe JAR will be created at app/build/libs/app.jar
./gradlew test- The server uses Java 21 virtual threads for efficient handling of multiple clients
- Server automatically shuts down after 30 seconds without new client connections (if no clients are connected)
- Messages are formatted as
[ClientName] message contentwhen broadcasted - The client polls for incoming messages while waiting for user input
This project is provided as-is for educational purposes.