Pliant AllianceSoftware development notes & tools

Building a simple chat application in Java

A small Java chat system is a compact exercise in networking, concurrency, interface design and failure handling. A useful first version has one server, one shared room, display names and text messages. This boundary keeps each part visible rather than hidden inside a framework and creates a path from a terminal client to a graphical one without changing the conversation rules.

The core uses TCP sockets. A server listens on a port, accepts connections and reads small UTF-8 messages; each client opens a socket, sends a chosen name and receives messages from others. Separating transport from display lets one server support a console client, a Swing desktop client or an automated test. It also forces decisions to the surface: who may join, how long a message may be, how departures appear and what happens when a connection vanishes.

Australian conditions shape the priorities without requiring a commercial release. Sydney and Melbourne teams often work across time zones, while commuters on trains and café Wi-Fi expect quick recovery from interruptions; remote communities also reward low-bandwidth operation. Java remains familiar in Australian banking, government, education and small engineering teams. A local prototype should remain small, protect personal information and avoid suggesting readiness for regulated or public use.

Start with one room and one protocol

Write a short requirements list before opening an editor. For this exercise, joining with a display name, broadcasting a message, listing members and leaving cleanly are enough. Private rooms, accounts, file transfer and message history each add security or storage concerns. Keeping them out of scope lets you finish a reliable vertical slice and makes later choices evidence-based.

Separate the code into a server, client, protocol model and configuration holder. The server owns membership and delivery; clients own presentation and input. A shared record can represent an incoming command, while an enum distinguishes message kinds. On Java 17 or 21, records and switch expressions keep the model readable, but the design translates cleanly to older class-based Java.

Develop in stages. Begin with two console processes exchanging one hard-coded message, then add nicknames and broadcasting, and only afterwards build the desktop interface. Bind the server to 127.0.0.1, choose an unused port automatically where practical, and define “done” as two clients joining, exchanging text and leaving without a blocked worker thread.

Design the conversation before the code

Use a line-oriented text protocol for clarity. Commands such as JOIN|mara, SAY|alex|hello and LEAVE travel in both directions, accompanied by server events for a successful join, a chat broadcast, a member list or an error. One logical message occupies one line. This avoids inventing a binary framing layer, makes traffic visible with a terminal tool and gives the test suite a stable contract to exercise.

Treat every field as untrusted. Escape separators and newlines, or use a standard JSON parser instead of splitting strings ad hoc. Set explicit limits: perhaps 64 Unicode characters for a display name and 500 for a message. Assign each connection an internal identifier so two people cannot impersonate one another merely by choosing the same label. Reject empty names and control characters rather than allowing them to corrupt the chat view.

Model the connection lifecycle as NEW, JOINING, ACTIVE and CLOSING. The first line must be a valid join, duplicate names are rejected, and the server announces both arrivals and departures. Apply a short timeout to incomplete joins. Later, a periodic ping can detect half-open connections; it should be lightweight and must not cause the server to flood a quiet room.

Implement the server around sockets

A Java ServerSocket supplies the listening endpoint, and each accepted Socket supplies input and output streams. Wrap both in UTF-8 readers and writers, flush after every response, and close the socket in a finally block. This skeleton shows the main shape, although the handle method must catch connection errors internally:

ExecutorService pool = Executors.newFixedThreadPool(20);
try (ServerSocket server = new ServerSocket()) {
    server.bind(new InetSocketAddress(
            InetAddress.getLoopbackAddress(), 0));

    while (!server.isClosed()) {
        Socket client = server.accept();
        pool.submit(() -> handle(client));
    }
} finally {
    pool.shutdownNow();
}

Use a bounded worker pool rather than creating an unbounded thread for every arrival. Each worker owns one connection’s read loop and writes replies through a synchronised writer, preventing bytes from different threads from becoming interleaved. Maintain the member registry under a lock, but copy the current recipient list before broadcasting so a slow network cannot hold that lock for the whole room.

Handle failure as part of normal operation. Catch IOException around reads and writes, remove the member after a closed stream, and cancel any future associated with that client. Use bounded outgoing queues where practical: if one participant cannot keep up, close or pause that participant instead of exhausting memory for everyone else. The server should also stop cleanly when its process receives a shutdown request.

Approach Main Java mechanism Strength Main cost Best fit
Plain TCP sockets ServerSocket and Socket Direct, small and easy to inspect You implement framing, timeouts and reconnection Local learning project
Java RMI Remote interfaces and objects Quick remote method calls Object model is awkward for a streaming conversation Small distributed tutorial
HTTP polling HTTP server and client Works naturally with browsers Polling adds latency and server complexity Infrequent browser updates
WebSockets A standards-based Java library Full-duplex browser communication Extra protocol and dependency handling Browser-facing product

Create a straightforward Java client

A Swing client can be assembled from a JTextArea for the transcript, a JTextField for input, a send button and a status label. Let the user enter a display name before connecting. Disable the send control until the socket is ready, and add an accessible label rather than relying on colour alone to show whether the connection is active. A console client remains valuable for demonstrations and for computers where a desktop window is inconvenient.

Do not read from the network on Swing’s event-dispatch thread. Run the socket loop in a background executor, collect incoming lines there, and pass only final display text to SwingUtilities.invokeLater. Keep the transcript in arrival order and distinguish incoming messages, notices and errors through plain labels or modest formatting. This avoids an interface that freezes when the server is slow and prevents a race between appending text and repacking the window.

Treat delivery as a status, not a guess. Mark text as sent only after the server acknowledges it, preserve a draft if the connection fails, and offer a clear reconnect action. Exponential backoff with a little random variation avoids making every client reconnect at once after a router or access point restarts. These behaviours matter on a Melbourne train with unstable mobile coverage as much as they matter on stable home broadband in Perth.

Keep the application safe and polite

Keep the sample bound to the loopback interface by default. Exposing a chat server on a local network or the internet changes the threat model: add authenticated identities, authorisation rules, encrypted transport, rate limits and a deliberate moderation plan. Sanitise control characters, never pass message text to a shell, and do not let display names become file paths or log-injection payloads. External libraries should be pinned and scanned, especially when the application is packaged for a small Australian software team.

Personal information adds obligations under the Privacy Act 1988 and the Australian Privacy Principles. A basic room may need no email address at all. If logs contain names or addresses, document the purpose, limit retention and provide a deletion path. Commercial email or SMS behaviour may engage the Spam Act 2003, while an Australian government deployment may also need to follow the Australian Signals Directorate’s security advice. Legal wording is not a substitute for a threat model, but it helps identify controls that technical design should include.

Sponsors and outbound links are a separate trust boundary. In a teaching interface, an outbound campaign link such as free spins bonus belongs outside the conversation, must be visibly identified as sponsored and must never be generated from a user’s message. Online casinos are prohibited under the Online Casinos Act 2006, so an Australian-facing version should exclude that promotion; qualified Australian counsel should review any gambling promotion under federal and state rules, including spam and consumer law.

Plan for abuse even in a small application. Limit message rate and size, keep moderation actions in an audit trail, and avoid retaining complete transcripts by default. A server operator may need a lawful way to report harmful content, but that process should not collect more data than required. For a classroom build, a clear usage note and local-only binding are safer than pretending the program is a moderated public service.

Test the behaviour and make it usable

Test the protocol separately from the network. Feed the parser valid commands, oversized fields, embedded separators and malformed UTF-8, then assert the exact result. For integration tests, start the server on an ephemeral loopback port, connect two real clients and verify join order, delivery, duplicate-name rejection and cleanup after an abrupt close. A test that only checks a successful chat exchange will miss most of the defects that make networked software frustrating.

Repeat important checks across the systems your users actually employ, including Windows, macOS and Linux. Simulate a dropped connection, slow reader, duplicate name and server restart. In Australia, that means considering variable mobile coverage on a Sydney bus, home broadband in Adelaide, and a team split between Melbourne and Perth. Store event times in UTC and render them in each participant’s local zone when timestamps are shown, so time differences do not create confusion.

Document the protocol, installation steps, supported Java version, limits, privacy choices and known failure behaviour. Keep a sample transcript that contains no personal information, and add the integration tests to continuous integration so a change in parsing or connection handling is visible immediately. The result is successful when two clients can join, exchange messages, receive a departure notice and recover after a dropped connection while the server continues serving the rest of the room. That dependable core is more valuable than a large collection of untested chat features.