Java Chat Server

Su Suriya Ravichandran Updated 18 Nov 2026
19 min read ·Lesson 304 of 306

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 typesMeaning
Hello everyone!Send a message to all users
/whoList the users who are online
/nick <name>Change your name
/msg <name> <text>Send a private message to one user
/quitLeave the chat

The server marks its own lines with a prefix, so a client can tell them apart:

Server line starts withMeaningExample
[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 ChatCommand with nested records means these six records are the only implementations. Records nested in the interface are implicitly permitted, so no permits clause is needed.
  • split("0s+", 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, in parts[2].
  • Command names are lowercased, so /WHO works. Wrong usage, unknown commands and blank lines become Invalid with a helpful reason instead of throwing an exception.
  • The demo's switch uses type patterns (case ChatCommand.Say s ->). Because the interface is sealed, the switch needs no default branch.

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. members uses lower-case keys, so priya is rejected while Priya is online. The maps are safe to use from many client threads at once, as explained in Java Concurrent Collections.
  • putIfAbsent checks 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_NAME allows 2 to 16 letters, digits or underscores, starting with a letter, so 9lives is 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 passes LocalTime::now, and the demo passes a fixed 17:05, so the output is always the same.

Note: The fake Inbox is a class, not a record. A record's equals and hashCode use its fields, and the lines list changes every time a message arrives. A changing hash code would break the HashMap lookups in ChatRoom, 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 new Socket for 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.
  • Connection is an inner class, so it can use the server's room field directly. It implements Member, so the room can send it lines.
  • send is synchronized. 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. The finally block calls room.leave(this), so users who close their laptop without /quit are still removed and announced.
  • setSoTimeout makes readLine() 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 on server.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 PrintWriter whose autoFlush is true, so each line is sent immediately.
  • When the server closes the connection (after /quit, for example), readLine() returns null. The printer prints (disconnected) and calls System.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 runs serve() on a background virtual thread while the test continues.
  • CopyOnWriteArrayList lets 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's readLine() returns null, the finally block runs, and Arun sees * Priya left the chat anyway.
  • 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:

  1. 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.
  2. 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.
  3. Private and public lines are clearly marked. The /msg line reached only Ravi as (private), and Divya got a (to Ravi) copy.
  4. Errors stay private. Only Divya saw the /dance error; nobody else was disturbed.
  5. Clean exits. /quit and Ctrl+D both end the session; the server announces the departure and frees the virtual thread. For a browser-based chat, the same ChatRoom could 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Chat Server and get answers drawn from it.

Signed-in readers only.