Java Chat Server
A Java chat server lets many people connect over TCP, pick a name and exchange messages in real time. Every message one user types is delivered to everyone else immediately, and users can also send private messages, list who is online and change their name. The project combines sockets, virtual threads, thread-safe collections and sealed interfaces in one working network program.
It follows the Java REST API Project. A REST API answers one request and forgets the client, while a chat server keeps every connection open and pushes messages to clients whenever something happens. You build a command parser, a chat room that delivers messages, the socket server, a console client and a scripted end-to-end test. All examples were run on JDK 21.
Design the Chat Protocol
Client and server talk in plain text: one message per line, encoded as UTF-8. Lines starting with / are commands; anything else is a chat message for everyone.
| User types | Meaning |
|---|---|
Hello everyone! | Send a message to all users |
/who | List the users who are online |
/nick <name> | Change your name |
/msg <name> <text> | Send a private message to one user |
/quit | Leave the chat |
The server marks its own lines with a prefix, so a client can tell them apart:
| Server line starts with | Meaning | Example |
|---|---|---|
[HH:mm] name: | A chat message | [17:05] Priya: Good morning, team! |
* | Information | * Arun joined the chat (2 online) |
! | An error for you only | ! no user named ravi |
(private) / (to name) | A private message received or sent | (private) Arun: can you share the slides? |
Parse Chat Commands With a Sealed Interface
Each typed line is turned into a ChatCommand object before anything else happens. A sealed interface lists every possible command, so a switch over it must handle all of them, and the compiler reports any case you forget.
package com.gocourse.chat;
/** Everything a user can type, parsed into one of these types. */
public sealed interface ChatCommand {
record Say(String text) implements ChatCommand { }
record Nick(String newName) implements ChatCommand { }
record PrivateMessage(String to, String text) implements ChatCommand { }
record Who() implements ChatCommand { }
record Quit() implements ChatCommand { }
record Invalid(String reason) implements ChatCommand { }
static ChatCommand parse(String line) {
String input = line.strip();
if (!input.startsWith("/")) {
return input.isEmpty() ? new Invalid("empty message") : new Say(input);
}
String[] parts = input.split("\\s+", 3); // command, first argument, rest of the line
return switch (parts[0].toLowerCase()) {
case "/nick" -> parts.length == 2 ? new Nick(parts[1]) : new Invalid("usage: /nick <name>");
case "/msg" -> parts.length == 3 ? new PrivateMessage(parts[1], parts[2])
: new Invalid("usage: /msg <name> <text>");
case "/who" -> new Who();
case "/quit" -> new Quit();
default -> new Invalid("unknown command " + parts[0] + ". Try /who, /nick, /msg or /quit");
};
}
}
package com.gocourse.chat;
public class CommandDemo {
public static void main(String[] args) {
String[] lines = {
"Hello everyone!",
"/nick Priya",
"/msg arun Are you joining the 5 pm call?",
"/WHO",
"/quit",
"/nick",
"/msg arun",
"/kick arun",
" ",
};
for (String line : lines) {
ChatCommand command = ChatCommand.parse(line);
String meaning = switch (command) {
case ChatCommand.Say s -> "broadcast \"" + s.text() + "\"";
case ChatCommand.Nick n -> "rename to " + n.newName();
case ChatCommand.PrivateMessage pm -> "private to " + pm.to() + ": " + pm.text();
case ChatCommand.Who w -> "list online users";
case ChatCommand.Quit q -> "leave the chat";
case ChatCommand.Invalid i -> "error: " + i.reason();
};
System.out.printf("%-42s -> %s%n", "\"" + line + "\"", meaning);
}
}
}
"Hello everyone!" -> broadcast "Hello everyone!"
"/nick Priya" -> rename to Priya
"/msg arun Are you joining the 5 pm call?" -> private to arun: Are you joining the 5 pm call?
"/WHO" -> list online users
"/quit" -> leave the chat
"/nick" -> error: usage: /nick <name>
"/msg arun" -> error: usage: /msg <name> <text>
"/kick arun" -> error: unknown command /kick. Try /who, /nick, /msg or /quit
" " -> error: empty message
How it works:
sealed interface ChatCommandwith nested records means these six records are the only implementations. Records nested in the interface are implicitly permitted, so nopermitsclause is needed.split(" 0 s+", 3)splits into at most three parts: the command, the first argument and the rest of the line. That keeps the whole private message text, spaces included, inparts[2].- Command names are lowercased, so
/WHOworks. Wrong usage, unknown commands and blank lines becomeInvalidwith a helpful reason instead of throwing an exception. - The demo's
switchuses type patterns (case ChatCommand.Say s ->). Because the interface is sealed, theswitchneeds nodefaultbranch.
Build the Chat Room That Delivers Messages
ChatRoom knows who is online and decides who receives each line. It talks to users only through a tiny Member interface, so it can be tested without any network code.
package com.gocourse.chat;
/** Anything that can receive chat lines: a socket connection, or a fake member in tests. */
public interface Member {
void send(String line);
}
package com.gocourse.chat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/** Keeps track of who is online and delivers messages. Safe to use from many threads at once. */
public class ChatRoom {
private static final Pattern VALID_NAME = Pattern.compile("[A-Za-z][A-Za-z0-9_]{1,15}");
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm");
/** Lower-case name -> member, so "Priya" and "priya" count as the same name. */
private final Map<String, Member> members = new ConcurrentHashMap<>();
private final Map<Member, String> names = new ConcurrentHashMap<>();
private final Supplier<LocalTime> clock;
public ChatRoom(Supplier<LocalTime> clock) {
this.clock = clock;
}
/** Tries to add a member under a name. Returns an error message, or null on success. */
public String join(Member member, String name) {
String problem = checkName(name);
if (problem != null) return problem;
if (members.putIfAbsent(name.toLowerCase(), member) != null) return "the name " + name + " is taken";
names.put(member, name);
broadcast("* " + name + " joined the chat (" + members.size() + " online)");
return null;
}
public void leave(Member member) {
String name = names.remove(member);
if (name != null) {
members.remove(name.toLowerCase());
broadcast("* " + name + " left the chat");
}
}
public void handle(Member member, ChatCommand command) {
String name = names.get(member);
switch (command) {
case ChatCommand.Say say -> broadcast("[" + clock.get().format(TIME) + "] " + name + ": " + say.text());
case ChatCommand.Nick nick -> rename(member, name, nick.newName());
case ChatCommand.PrivateMessage pm -> {
Member target = members.get(pm.to().toLowerCase());
if (target == null) {
member.send("! no user named " + pm.to());
} else {
target.send("(private) " + name + ": " + pm.text());
member.send("(to " + names.get(target) + ") " + pm.text());
}
}
case ChatCommand.Who who -> member.send("* online: " + String.join(", ", onlineNames()));
case ChatCommand.Quit quit -> leave(member);
case ChatCommand.Invalid invalid -> member.send("! " + invalid.reason());
}
}
public List<String> onlineNames() {
return names.values().stream().sorted(String.CASE_INSENSITIVE_ORDER).toList();
}
private void rename(Member member, String oldName, String newName) {
String problem = checkName(newName);
if (problem != null) {
member.send("! " + problem);
return;
}
if (members.putIfAbsent(newName.toLowerCase(), member) != null && !newName.equalsIgnoreCase(oldName)) {
member.send("! the name " + newName + " is taken");
return;
}
if (!newName.equalsIgnoreCase(oldName)) members.remove(oldName.toLowerCase());
names.put(member, newName);
broadcast("* " + oldName + " is now known as " + newName);
}
private static String checkName(String name) {
if (name == null || !VALID_NAME.matcher(name).matches()) {
return "names must be 2-16 letters, digits or _, starting with a letter";
}
return null;
}
private void broadcast(String line) {
for (Member m : names.keySet()) m.send(line);
}
}
The demo uses fake members that store every line they receive:
package com.gocourse.chat;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
public class RoomDemo {
/** A fake member that just remembers what it received. A class, not a record: see below. */
static class Inbox implements Member {
final String label;
final List<String> lines = new ArrayList<>();
Inbox(String label) {
this.label = label;
}
@Override
public void send(String line) {
lines.add(line);
}
}
public static void main(String[] args) {
ChatRoom room = new ChatRoom(() -> LocalTime.of(17, 5));
Inbox priya = new Inbox("priya");
Inbox arun = new Inbox("arun");
Inbox guest = new Inbox("guest");
System.out.println("join Priya -> " + room.join(priya, "Priya"));
System.out.println("join Arun -> " + room.join(arun, "Arun"));
System.out.println("join priya -> " + room.join(guest, "priya"));
System.out.println("join 9lives -> " + room.join(guest, "9lives"));
System.out.println("join Meena -> " + room.join(guest, "Meena"));
room.handle(priya, ChatCommand.parse("Hi all, standup in 5 minutes"));
room.handle(arun, ChatCommand.parse("/msg priya I will be 2 minutes late"));
room.handle(guest, ChatCommand.parse("/msg ravi hello?"));
room.handle(guest, ChatCommand.parse("/nick arun"));
room.handle(guest, ChatCommand.parse("/nick MeenaK"));
room.handle(arun, ChatCommand.parse("/who"));
room.handle(priya, ChatCommand.parse("/quit"));
for (Inbox inbox : List.of(priya, arun, guest)) {
System.out.println("\n--- what " + inbox.label + " received ---");
inbox.lines.forEach(System.out::println);
}
}
}
join Priya -> null
join Arun -> null
join priya -> the name priya is taken
join 9lives -> names must be 2-16 letters, digits or _, starting with a letter
join Meena -> null
--- what priya received ---
* Priya joined the chat (1 online)
* Arun joined the chat (2 online)
* Meena joined the chat (3 online)
[17:05] Priya: Hi all, standup in 5 minutes
(private) Arun: I will be 2 minutes late
* Meena is now known as MeenaK
--- what arun received ---
* Arun joined the chat (2 online)
* Meena joined the chat (3 online)
[17:05] Priya: Hi all, standup in 5 minutes
(to Priya) I will be 2 minutes late
* Meena is now known as MeenaK
* online: Arun, MeenaK, Priya
* Priya left the chat
--- what guest received ---
* Meena joined the chat (3 online)
[17:05] Priya: Hi all, standup in 5 minutes
! no user named ravi
! the name arun is taken
* Meena is now known as MeenaK
* Priya left the chat
How it works:
- Two
ConcurrentHashMaps link names and members in both directions.membersuses lower-case keys, sopriyais rejected whilePriyais online. The maps are safe to use from many client threads at once, as explained in Java Concurrent Collections. putIfAbsentchecks and claims a name in one atomic step. If two users try to take the same name at the same moment, only one of them succeeds.VALID_NAMEallows 2 to 16 letters, digits or underscores, starting with a letter, so9livesis refused. Names can never contain spaces, which keeps/msg <name> <text>easy to parse.- A private message goes to the target and a copy (
(to Priya) ...) goes back to the sender, so both see the conversation. - The time comes from a
Supplier<LocalTime>. The real server passesLocalTime::now, and the demo passes a fixed17:05, so the output is always the same.
Note: The fake
Inboxis a class, not a record. A record'sequalsandhashCodeuse its fields, and thelineslist changes every time a message arrives. A changing hash code would break theHashMaplookups inChatRoom, so members must use normal identity equality.
Accept Many Clients With ServerSocket and Virtual Threads
ChatServer opens a ServerSocket and waits for connections. Each connected user runs on its own virtual thread, which can block on readLine() for minutes without using an operating-system thread.
package com.gocourse.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.time.LocalTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
/** A multi-user TCP chat server. Each client gets its own virtual thread. */
public class ChatServer implements AutoCloseable {
private final ServerSocket serverSocket;
private final ChatRoom room;
private final ExecutorService clients = Executors.newVirtualThreadPerTaskExecutor();
/** Port 0 picks any free port. The clock lets demos and tests use a fixed time. */
public ChatServer(int port, Supplier<LocalTime> clock) throws IOException {
serverSocket = new ServerSocket(port);
room = new ChatRoom(clock);
}
public int port() {
return serverSocket.getLocalPort();
}
/** Accepts clients until the server socket is closed. */
public void serve() {
while (!serverSocket.isClosed()) {
try {
Socket socket = serverSocket.accept();
Connection connection = new Connection(socket);
clients.submit(connection::run);
} catch (IOException e) {
if (!serverSocket.isClosed()) System.err.println("accept failed: " + e.getMessage());
}
}
}
@Override
public void close() throws IOException {
serverSocket.close();
clients.shutdownNow();
}
/** One connected user: reads their lines and passes them to the room. */
private class Connection implements Member {
private final Socket socket;
private final PrintWriter out;
Connection(Socket socket) throws IOException {
this.socket = socket;
this.out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
}
@Override
public synchronized void send(String line) { // one line at a time, never mixed with another
out.println(line);
}
void run() {
try (socket;
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8))) {
socket.setSoTimeout(10 * 60 * 1000); // drop clients that stay silent for 10 minutes
if (!login(in)) return;
String line;
while ((line = in.readLine()) != null) {
ChatCommand command = ChatCommand.parse(line);
room.handle(this, command);
if (command instanceof ChatCommand.Quit) {
send("* bye!");
return;
}
}
} catch (SocketException e) {
// the client disconnected abruptly: nothing to report
} catch (IOException e) {
System.err.println("connection error: " + e.getMessage());
} finally {
room.leave(this); // safe even if the user already left with /quit
}
}
/** Asks for a name until one is accepted. Returns false if the client disconnects first. */
private boolean login(BufferedReader in) throws IOException {
send("Welcome to GOCOURSE chat! Type your name:");
String name;
while ((name = in.readLine()) != null) {
String problem = room.join(this, name.strip());
if (problem == null) {
send("* commands: /who /nick <name> /msg <name> <text> /quit");
return true;
}
send("! " + problem + ". Try again:");
}
return false;
}
}
public static void main(String[] args) throws IOException {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 5000;
try (ChatServer server = new ChatServer(port, LocalTime::now)) {
System.out.println("Chat server listening on port " + server.port());
server.serve();
}
}
}
How it works:
serverSocket.accept()blocks until a client connects and returns a newSocketfor that client. The loop then hands the connection to the executor and immediately waits for the next one, as in Java ServerSocket.newVirtualThreadPerTaskExecutor()starts one virtual thread per client. A thousand idle users cost very little memory, because a blocked virtual thread releases its carrier thread.Connectionis an inner class, so it can use the server'sroomfield directly. It implementsMember, so the room can send it lines.sendissynchronized. Two threads might deliver lines to the same user at once (for example, a broadcast and a private message), and the lock makes sure each line is written whole.try (socket; BufferedReader in = ...)closes both the reader and the socket at the end. Thefinallyblock callsroom.leave(this), so users who close their laptop without/quitare still removed and announced.setSoTimeoutmakesreadLine()throw after 10 silent minutes, which frees the thread of a client whose network died without closing the connection.
Write the Java Chat Client
The client must do two things at once: show lines from the server whenever they arrive, and send lines the user types. It uses a second (virtual) thread for printing while the main thread reads the keyboard.
package com.gocourse.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/** Console client: one thread prints what the server sends, the main thread sends what you type. */
public class ChatClient {
public static void main(String[] args) throws IOException {
String host = args.length > 0 ? args[0] : "localhost";
int port = args.length > 1 ? Integer.parseInt(args[1]) : 5000;
try (Socket socket = new Socket(host, port);
BufferedReader server = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
PrintWriter toServer = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) {
Thread printer = Thread.ofVirtual().start(() -> {
try {
String line;
while ((line = server.readLine()) != null) System.out.println(line);
} catch (IOException e) {
// socket closed: the main thread is finishing
}
System.out.println("(disconnected)");
System.exit(0); // stop waiting for keyboard input
});
String typed;
while ((typed = keyboard.readLine()) != null) {
toServer.println(typed);
}
socket.shutdownOutput(); // Ctrl+D: tell the server we are done
printer.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
How it works:
Thread.ofVirtual().start(...)starts the printer thread. It loops onserver.readLine()and prints each line, so messages from other users appear even while you are typing.- The main thread copies keyboard lines to the server with a
PrintWriterwhoseautoFlushistrue, so each line is sent immediately. - When the server closes the connection (after
/quit, for example),readLine()returnsnull. The printer prints(disconnected)and callsSystem.exit(0), because the main thread would otherwise keep waiting for keyboard input. - Pressing Ctrl+D (Ctrl+Z then Enter on Windows) ends keyboard input.
socket.shutdownOutput()tells the server that no more lines will come, and the server removes the user. The basics of client sockets are covered in Java Socket.
Test the Chat Server With Scripted Users
A real network test starts the server on a free port, connects several clients over TCP and checks what each one received. Each Bot collects incoming lines on its own virtual thread.
package com.gocourse.chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** Starts a real server on a free port and connects three scripted users over TCP. */
public class NetworkDemo {
static class Bot implements AutoCloseable {
final String label;
final Socket socket;
final PrintWriter out;
final List<String> received = new CopyOnWriteArrayList<>();
Bot(String label, int port) throws Exception {
this.label = label;
socket = new Socket("localhost", port);
out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
Thread.ofVirtual().start(() -> {
try {
String line;
while ((line = in.readLine()) != null) received.add(line);
} catch (Exception ignored) {
// socket closed
}
});
}
void type(String line) throws InterruptedException {
out.println(line);
Thread.sleep(150); // give the server time to deliver before the next step
}
@Override
public void close() throws Exception {
socket.close();
}
}
public static void main(String[] args) throws Exception {
ChatServer server = new ChatServer(0, () -> LocalTime.of(17, 5));
Thread.ofVirtual().start(server::serve);
try (Bot priya = new Bot("Priya", server.port());
Bot arun = new Bot("Arun", server.port());
Bot meena = new Bot("Meena", server.port())) {
priya.type("Priya");
arun.type("priya"); // taken (names ignore case)
arun.type("Arun");
meena.type("Meena");
priya.type("Good morning, team!");
meena.type("/who");
arun.type("/msg Meena can you share the slides?");
meena.type("/msg arun sent!");
meena.type("/quit");
priya.socket.close(); // Priya's laptop goes to sleep: no /quit
Thread.sleep(300);
for (Bot bot : List.of(priya, arun, meena)) {
System.out.println("--- " + bot.label + "'s screen ---");
bot.received.forEach(System.out::println);
System.out.println();
}
}
server.close();
}
}
--- Priya's screen ---
Welcome to GOCOURSE chat! Type your name:
* Priya joined the chat (1 online)
* commands: /who /nick <name> /msg <name> <text> /quit
* Arun joined the chat (2 online)
* Meena joined the chat (3 online)
[17:05] Priya: Good morning, team!
* Meena left the chat
--- Arun's screen ---
Welcome to GOCOURSE chat! Type your name:
! the name priya is taken. Try again:
* Arun joined the chat (2 online)
* commands: /who /nick <name> /msg <name> <text> /quit
* Meena joined the chat (3 online)
[17:05] Priya: Good morning, team!
(to Meena) can you share the slides?
(private) Meena: sent!
* Meena left the chat
* Priya left the chat
--- Meena's screen ---
Welcome to GOCOURSE chat! Type your name:
* Meena joined the chat (3 online)
* commands: /who /nick <name> /msg <name> <text> /quit
[17:05] Priya: Good morning, team!
* online: Arun, Meena, Priya
(private) Arun: can you share the slides?
(to Arun) sent!
* bye!
How it works:
new ChatServer(0, ...)binds to any free port, and the server runsserve()on a background virtual thread while the test continues.CopyOnWriteArrayListlets the reader thread add lines while the main thread later reads them, without extra locking.- Arun's first name,
priya, is refused because names ignore case, and he is asked again. The login loop does not let anyone chat before choosing a valid name. - Priya closes her socket without
/quit. On the server, her connection'sreadLine()returnsnull, thefinallyblock runs, and Arun sees* Priya left the chatanyway. - The short
Thread.sleep(150)after each line keeps the steps in order, so every run prints exactly the same screens.
Real-World Example: Run a Team Chat on Your Network
chat-server/
└── src/
└── com/
└── gocourse/
└── chat/
├── ChatClient.java
├── ChatCommand.java
├── ChatRoom.java
├── ChatServer.java
└── Member.java
cd chat-server
javac -d out src/com/gocourse/chat/*.java
jar --create --file chat.jar -C out .
# terminal 1: the server
java -cp chat.jar com.gocourse.chat.ChatServer 5000
Chat server listening on port 5000
Ravi and Divya each open a terminal and start the client. On another computer in the same network, replace localhost with the server's IP address, such as 192.168.1.20.
java -cp chat.jar com.gocourse.chat.ChatClient localhost 5000
Ravi's terminal (the lines he typed are Ravi, Hello! Anyone here?, /who, /nick ravi_k and /quit):
Welcome to GOCOURSE chat! Type your name:
Ravi
* Ravi joined the chat (1 online)
* commands: /who /nick <name> /msg <name> <text> /quit
* Divya joined the chat (2 online)
Hello! Anyone here?
[06:54] Ravi: Hello! Anyone here?
[06:54] Divya: Hi Ravi, welcome!
/who
* online: Divya, Ravi
(private) Divya: The meeting link is in the group
/nick ravi_k
* Ravi is now known as ravi_k
/quit
* bye!
(disconnected)
Divya's terminal (she typed Divya, Hi Ravi, welcome!, the /msg line and /dance, then pressed Ctrl+D):
Welcome to GOCOURSE chat! Type your name:
Divya
* Divya joined the chat (2 online)
* commands: /who /nick <name> /msg <name> <text> /quit
[06:54] Ravi: Hello! Anyone here?
Hi Ravi, welcome!
[06:54] Divya: Hi Ravi, welcome!
/msg ravi The meeting link is in the group
(to Ravi) The meeting link is in the group
* Ravi is now known as ravi_k
/dance
! unknown command /dance. Try /who, /nick, /msg or /quit
* ravi_k left the chat
(disconnected)
How it works:
- Real-time delivery. Divya saw Ravi's greeting the moment he sent it, while her own client was waiting for keyboard input. That is the printer thread at work.
- Echo of your own messages. A broadcast goes to everyone, including the sender, so each user sees the server's timestamped version of what they typed.
- Private and public lines are clearly marked. The
/msgline reached only Ravi as(private), and Divya got a(to Ravi)copy. - Errors stay private. Only Divya saw the
/danceerror; nobody else was disturbed. - Clean exits.
/quitand Ctrl+D both end the session; the server announces the departure and frees the virtual thread. For a browser-based chat, the sameChatRoomcould sit behind a WebSocket endpoint instead, as introduced in Java WebSocket.
The next project, the Java Employee Manager, manages staff records with departments, salaries, raises, an org chart and payroll reports.