| CPSC 329 | Software Development | Fall 2026 |
Lab 10 provided practice with threads on the server side: supporting multiple clients and handling the thread safety issues that arise with shared state. This lab focuses on protocol, conversation and model state, client threads, and code organization — things that come up as the interactions between client and server become more complex.
Successful completion of this lab means that you:
Labs are for learning and practice — you may help and be helped by others when it comes to figuring out what to do, but in the end you need to understand and be able to do the things for yourself.
This lab can be done individually or in pairs. If you work together, use pair programming rather than splitting things up and working in parallel.
You may not use AI to figure out what to do or to do the task for you.
due Fri 11/20 at the start of class
To hand in your work:
If you worked with someone else, make sure both partners are named in @author tags in the main Javadoc comment for any classes you edited. Only one needs to hand in the lab.
Copy your entire ~/cs329/dev/lab11 directory into your handin directory. Make sure you end up with lab11 (directly) inside your handin directory and that it contains a src directory (with your code) — you shouldn't have a bunch of stuff loose in the top level of your handin directory or have folders nested deeper.
Players join the room and can submit riddles at any time. The server keeps the submitted riddles in a queue. There is one current riddle, posed to everyone in the room; when someone answers it correctly, everyone is told, and the next riddle in the queue becomes the current riddle. If the queue is empty, there's no current riddle until someone submits one. You can't answer your own riddle.
In this version, a riddle only ends when someone answers it correctly — if no one knows the answer, all the players can do is leave and hope that eventually someone who knows the answer will show up. Optional extensions address this problem by allowing a riddle to end unsolved: its submitter can reveal the answer or leave, or everyone can give up.
The riddle room's protocol follows the same style as the joke server's: a message starts with a command word, possibly followed by more words on the same line (its arguments). When the messages need to contain content that could include spaces (such as a riddle or its answer), the line with the command is followed by additional lines containing the content.
| sender | message | meaning |
|---|---|---|
| server | hello riddleroom/1 | sent when a client connects — the server speaks first |
| client | join name | join the room (name is one word) |
| server | welcome name | joined; followed by the current riddle (a riddle message), if there is one |
| server | joined name left name | another player joined or left the room (sent to everyone else in the room) |
| client | submit riddle + 2 more lines: the riddle, the answer | add a riddle to the queue |
| server | submitted | the riddle was added |
| server | riddle submitter + 1 more line: the riddle | a new current riddle (sent to everyone) |
| client | answer + 1 more line: the answer | answer the current riddle |
| server | incorrect | the answer was wrong (sent only to the player who answered) |
| server | solved name + 1 more line: the answer | the current riddle was solved by name (sent to everyone); the next riddle (if any) follows |
| client | quit | leave the room; the server closes the connection |
| server | error reason | the client's message was rejected; nothing changed |
A client which closes the connection or loses it (without sending quit) is treating as having left the room (the server sends a left message to everyone).
The error replies, and the reason each is rejected:
| reply | when | rejected because of |
|---|---|---|
| error usage: join name (one word) | join without a name, or with more than one word | the message's format |
| error can't submit kind | submit followed by anything other than riddle | the message's format |
| error unknown command: command | a command the server doesn't know | the message's format |
| error join first | submit riddle or answer before joining | conversation state |
| error already joined | join after joining | conversation state |
| error the name name is already taken | join with the name of a player already in the room | model state |
| error the riddle and answer can't be empty | submit riddle with an empty riddle or answer | the message's content |
| error no riddle right now | answer when there's no current riddle | model state |
| error you can't answer your own riddle | answer when you submitted the current riddle | model state |
A message that's rejected still has its extra lines read: a rejected submit riddle or answer is followed by its riddle and answer, or its answer, just as an accepted one is. Otherwise those lines would be read as the client's next commands.
The sequence diagram below shows the protocol in action with alice and bob as two players. (Lines in ‹› stand for the actual content.) Note that when there's no current riddle, the submitted riddle is posed right away — so the riddle message reaches alice before the submitted reply to her request.

The code is in two packages, organized by whether it is used by the client or the server. Nothing is shared between them: the client and the server know each other only through the protocol.
server, organized like the auction server from class:
client:
Create an Eclipse project and share it to a local Git repository:
Create a new Eclipse project named lab11. Remember that the project directory should end up under ~/cs329/dev, not in Eclipse's workspace.
Import all of the files from /classes/cs329/lab11 into your project, preserving the directory structure — the Java files should end up in the client and server packages under src.
Confirm that the project builds with no errors.
Create a new (local) Git repository, create/set up .gitignore, and do the initial commit. Include a meaningful commit message (e.g. "Added lab starter files").
As in lab 10, run the server in Eclipse and the clients in terminal windows:
Start the server (RoomServer, in the server package) in Eclipse. Be sure to stop and restart the server each time you change its code. (If the server reports "Address already in use", another copy of the server is still running — find the Eclipse console with the running server and stop it.)
Open one terminal window for each client, and in each one, cd to the project's bin directory:
cd ~/cs329/dev/lab11/bin
The client takes the server's host and port as arguments (the server listens on port 9060). Since RoomClient is in the client package, include the package name:
java client.RoomClient localhost 9060
Type help in a client for the list of commands. Note that the commands you type aren't the protocol (though they may be similar): the client turns them into protocol messages. For example, submit asks for the riddle and the answer, then sends submit riddle followed by the two lines, and answer text sends answer and text on separate lines.
To stop a program which is running in a terminal, press ctrl-C in its window.
Work through the parts below in order. Places where you need to add code are marked with TODO comments in the provided code, labeled with the specific steps (e.g. 2c, 4a).
The provided client is lockstep like the joke server's clients: after sending a message, it reads from the server until the reply it is waiting for arrives (readUntilReply). It doesn't read from the server at any other time.
Run and observe, watching each client as you go:
The server sends messages that the client didn't ask for — the current riddle after the welcome, other players joining and leaving, new riddles — and the lockstep client only finds out about them when it next happens to read from the server. The joke server never sent anything the client hadn't asked for, so being lockstep was fine there.
The riddle room is different from the joke server in other ways too:
| joke server (lab 10) | riddle room | |
|---|---|---|
| messages the client didn't ask for | none: every message from the server is a reply | joins, departures, new riddles, solved riddles |
| conversation state | implicit: where the handler is in its code (in the middle of tellRiddle, whatever line arrives next is the answer) | explicit: ClientHandler's Phase, checked for each message |
| model state | none: any riddle can be asked for at any time | the current riddle and the queue, in Room |
| shared data and rules | a plain list, locked by the handlers | Room, which locks its own data and enforces the rules |
| how a change reaches other clients | (it doesn't) | the room notifies its listeners (the ClientHandlers), which send messages |
To show messages as soon as they arrive, the client needs a thread which does nothing but wait for and handle messages from the server, while the main thread waits for the user to type commands. The connection to the server is a job of its own, so first it gets a class of its own — like ServerConnection in the auction client from class. The connection will then be the task run by the listener thread.
Write code (2a): create a class ServerConnection in the client package and move the connection-related elements of RoomClient to it (cut and paste):
the instance variables socket_, in_, and out_
the part of RoomClient's constructor that makes the connection and creates the streams — it becomes the body of a constructor ServerConnection(String host, int port)
the three send methods and readLine — make them public
Then fix up the problems — the compiler's red error markers show what still needs fixing:
Pass along exceptions generated in ServerConnection methods (including the constructor) by declaring a throws in the method headers.
Run and check: the client works just as before (minus look). This step only reorganized the code — it shouldn't change what the program does.
Commit your work.
Write code (2b): make ServerConnection implement Runnable, with a run method which listens for messages from the server and has the client handle each one:
@Override
public void run () {
try {
for ( ; true ; ) {
String line = in_.readLine();
if ( line == null ) { // the server closed the connection
break;
}
client_.handleMessage(line);
}
} catch ( IOException e ) {
// the connection was closed or failed
}
client_.connectionClosed();
}
client_ is the RoomClient whose handleMessage is called: add an instance variable for it, and a constructor parameter to set it. (RoomClient passes this when it creates its ServerConnection.) connectionClosed will be marked as an error until the next step.
Note that handleMessage reads the extra lines of a message with connection_.readLine() — it runs on the listener thread, so all reading from the server is still done by one thread.
Write code (2c): when the connection closes, the main thread (waiting for the user to type) needs to find out so that it stops. In RoomClient, add a flag:
// written by the connection's thread when the connection closes, read // by the keyboard thread private volatile boolean connected_;
Set it to true in the constructor and add the method the connection calls when it closes:
/**
* The connection to the server has been closed. Called by the
* connection's thread.
*/
public void connectionClosed () {
if ( connected_ ) { // not already closed because the user quit
connected_ = false;
System.out.println("[connection closed - press Enter to exit]");
}
}
In run, make the keyboard loop continue only while connected_ is true and set connected_ to false when the user types quit, before sending quit to the server.
Write code (2d): in RoomClient.run, start a thread to run the connection in place of the readUntilReply("hello",null) call:
Thread listener = new Thread(connection_,"server-connection"); listener.start();
Then remove the lockstep code: the other calls to readUntilReply (marked TODO 2d) and the readUntilReply method itself. (If Eclipse then reports that an IOException is never thrown, remove that try/catch or throws.)
Run and check: repeat the steps from part 1. The current riddle, other players joining and leaving, and new riddles should now appear as soon as they happen. Also try stopping the server while a client is running.
Commit your work.
The lockstep client's state was implicit — while it was inside readUntilReply("welcome","error"), it was "waiting to find out whether I joined" — just like the joke server's handler. Now that messages can arrive at any time, the client keeps its state explicitly and changes it when handleMessage handles a message: whether it has joined (name_), whether the connection is still open (connected_), and its copy of the room's state (whether there's a current riddle, and who submitted it). That copy is only for showing the user what's going on (and for convenience checks) — the server's model is the one that counts. (The blue transitions come in part 4.)

Note that the auction client defined specific phases (WAITING_FOR_HELLO, NOT_JOINED, etc) — that's useful when there are many conversation states. In this case there are only a few so the client's state is simply what its instance variables say: name_ is null until the client has joined, currentSubmitter_ is null when there's no current riddle, and connected_ says whether the connection is still open.
Also note what the client doesn't keep track of: whether it's waiting for a reply. It doesn't need to since it just shows each reply when it arrives. A GUI client would likely want such a state — for example, to disable an Answer button between sending an answer and getting incorrect or solved back, like the "bid pending" state of the auction client from class.
Part 4 adds answering a riddle, which is already in the protocol table above: the client sends answer followed by a line with the answer, the server replies incorrect to the player who answered, or tells everyone solved — followed by the next riddle, if there is one. This part shows that piece of the protocol in the diagrams; there's nothing to write.
The sequence diagram shows four scenarios (highlighted): an incorrect answer, a correct answer with another riddle waiting in the queue, alice trying to answer her own riddle, and two correct answers sent at nearly the same time.

There are two kinds of state that decide what happens when a message arrives at the server. Each connection has its own conversation state — has this client joined yet? — which ClientHandler keeps (its Phase). The room itself has model state — is there a current riddle? — which is the same for everyone; Room keeps it. A request can be rejected because of either one: submit riddle before joining is rejected because of the conversation state, while an answer when there's no current riddle is rejected because of the room's state.
Both kinds of state are shown in state diagrams. (event / action on each arrow is the message which arrives, or what happens, and what the server does in response.) The additions for answering are in blue, which you'll be implementing in the next part.
For the connection's conversation state:

For the room's model state (NO_RIDDLE and so on are the outcomes the room reports back to the handler):

The design decisions behind this part of the protocol:
The answer goes on its own line, since it can contain spaces — the same choice as for submit riddle.
incorrect goes only to the player who answered; solved goes to everyone. A reply to a request goes to the client which made it, while a change to the room is reported to everyone. There's no separate "correct" reply: the player who answered finds out from solved, like everyone else.
The server decides which of two simultaneous correct answers wins. No client could — only the server sees everyone's answers. The second one finds that the riddle is no longer current.
Answering can be rejected because of either kind of state. Answering before joining is rejected because of the conversation state, by ClientHandler. Answering when there's no current riddle, or answering your own riddle, is rejected because of the model state, by Room — the rules of the room belong to the room.
The room reports an outcome, not a message. Room.answer returns a Room.AnswerResult (CORRECT, INCORRECT, NO_RIDDLE, or OWN_RIDDLE) and ClientHandler decides what to send. All of the protocol's message text stays in one place.
One gap in what's implemented: a riddle nobody can answer would stay the current riddle forever. That's what reveal and revealed are for, but they aren't part of this lab (except as an extension).
Adding answer involves every part of the server and the client. Here's how a message flows through the server, using submit riddle (which is already implemented) as an example:
ClientHandler.run reads a line from the client and, based on the command word, calls a handleX method (handleSubmit).
The handleX method reads any extra lines of the message (the riddle and the answer), checks the conversation state (has the client joined?), and calls the model (room_.submit).
The model (Room) checks the rules and changes its state, and if something changed that other players need to know about, calls a RoomListener method on each of its listeners (riddlePosed, if there was no current riddle).
Each ClientHandler, as a listener, turns the notification into a message to its own client (riddle submitter and the riddle).
Back in the handleX method, a reply is sent to the client which made the request (submitted).
In MVC terms, Room is the model and ClientHandler is the view for one remote player: run is its input and sending to the client is its output. The handleX methods act as the controller. Because the handler is also the room's listener, all of the protocol — reading and writing messages — is in one class. (With a big protocol, the handleX methods could be moved into a separate controller class to keep ClientHandler from getting too big.)
Note also that a listener method such as riddlePosed is called by whichever thread changed the room — often another client's handler thread. That's why ClientHandler's send methods are synchronized: several threads may send to the same client.
Write code (4a): in Room, write answer. It checks the rules, and if the answer is correct, tells the listeners and moves on to the next riddle:
if ( current_ == null ) {
return AnswerResult.NO_RIDDLE;
}
// TODO: return OWN_RIDDLE if name is the current riddle's submitter,
// and INCORRECT if the answer is wrong
QueuedRiddle solved = current_;
for ( RoomListener listener : listeners_ ) {
listener.riddleSolved(name,solved);
}
advance();
return AnswerResult.CORRECT;
Fill in the two missing checks, using the current riddle's getSubmitter and its Riddle's isCorrect. (advance is provided: it makes the next riddle in the queue the current riddle and tells the listeners, or leaves no current riddle if the queue is empty.)
Since answer is synchronized, the checks and the change happen while holding the room's lock. That's lab 10's check-then-act, now handled by the class itself: if two players answer correctly at nearly the same time, the second one waits for the lock, then finds a different current riddle (or none). And since the listeners are notified while the lock is held, every client gets solved before the next riddle.
Write code (4b): in ClientHandler, write handleAnswer, using handleSubmit as a model:
Read the answer (the next line). If it's null, the client has gone: throw an IOException. Read it before checking anything else — even if the answer is going to be rejected, its line must be read, or it would be read as the client's next command and the conversation would be out of step.
If the client hasn't joined, send error join first.
Otherwise call room_.answer, and send the reply for the outcome, to this client only:
| outcome | reply |
|---|---|
| INCORRECT | incorrect |
| NO_RIDDLE | error no riddle right now |
| OWN_RIDDLE | error you can't answer your own riddle |
| CORRECT | nothing — riddleSolved tells everyone, including this client |
Then fill in riddleSolved, which turns the room's notification into a message:
send("solved " + name,riddle.getRiddle().getAnswer());
Calling riddleSolved is handled by the call to room_.answer, whose return value is being handled here — room_.answer does the model work for a submitted answer and handleAnswer is managing the client communications around that.
Write code (4c): in RoomClient:
In handleCommand, send the answer the user typed (answer text):
connection_.send("answer",arg);
In handleMessage, add cases for incorrect and solved. Model them on the other cases — solved is followed by a line with the answer (see how riddle reads its extra line), then there's no current riddle until the next riddle message arrives, so set currentSubmitter_ to null.
Optional: the client knows its own name and who submitted the current riddle, so it could refuse to send an answer to your own riddle and tell the user right away. Add that check if you like — the server still checks.
Run and check with three clients (you'll need to know the answers to the starter riddles: a mountain, wind, and an egg):
Commit your work.
You don't need to hand in anything for this part, but you should think about and answer the questions for yourself to make sure you understand what is going on.
For part 2:
The joke server's clients were lockstep (send, then read the reply) and that worked fine. Why doesn't it work for the riddle room?
Now that the client has a listener thread, how many threads read from the client's socket? How many write to it? Why does that matter?
For part 4:
An answer can be rejected in three ways: before joining, when there's no current riddle, and when it's your own riddle. Which of these are rejected because of the connection's conversation state and which because of the room's (model) state? Which class checks each one, and why there?
Room.answer tells the listeners the riddle was solved and poses the next riddle while it holds the room's lock. What does that guarantee for the clients? What could go wrong if two players sent a correct answer at nearly the same time and the check and the change weren't done under the same lock?
The client can refuse to send an answer to your own riddle. Why does the server check anyway?
This part is optional. If you have time, add one or more of the following.
Reveal: let the submitter of the current riddle end it unsolved with reveal, which tells everyone revealed name and the answer, then poses the next riddle. First work out the design: add reveal to the sequence diagram (when it's allowed, and when it's rejected) and to both state diagrams. You can sketch these on paper. What should happen if someone other than the submitter tries it? Then implement it, following the same path as answer: a reveal method in Room, a new riddleRevealed method in RoomListener, a handleReveal method and a listener method in ClientHandler, and the command and message in RoomClient.
A submitter who leaves: according to the protocol, if a riddle's submitter leaves while it's the current riddle, its answer is revealed. Implement that in Room.leave (using riddleRevealed from the previous extension). What should happen to riddles the player submitted that are still in the queue? Decide, and explain your decision in a comment.
Give up: another way for a riddle to end unsolved. Any player (except the submitter) can give up on the current riddle; once everyone except the submitter has given up, the answer is revealed. This needs the room to keep track of who has given up, and to check everyone's state while holding the lock. What should happen when the last player who hasn't given up leaves?