CM10228
/ Programming Ib: Lab
2
Concurrency and Networking: Chat Application
<<
Back to contents
Now that you know how to make clients and servers, and have
them
both threaded, the only thing left to do is to let the multiple clients
interact with each other. This is actually reasonably simple, and is
just pure Java. You already know all the networking and all the
threading that you need to know to do this. And in fact, your clients
from the previous section should be already capable of sending and
receiving messages in this chat program (although you might want to add
a prompt to distinguish between what you are typing and what came from
the server).
Do this:
- Task:
- Create a server
which accepts multiple client connections. When a message is received
from a client, broadcast this message to all the other clients (and the
sender if you wish).
- If you have time, try one or more of these bonus
objectives:
- When a client connects, ask for their name. Now
whenever
a client sends a message, prefix their name to the message that is
broadcast.
- Can you deal with clients connecting and disconnecting
mid-way through the conversation?
- Come up with a protocol for your chat room. Make your
server announce when people join or leave the conversation, using some
identifier so everyone knows the message is from the server.
- You might want to stop people abusing your chat room
- Add a character limit to each message (prevent
anything over this being sent, and warn the user from the server that
it wasn't sent).
- Disconnect users who try to send too many messages in
a short time, or who keep trying to send messages that are too long.
In summary: you have learned how to spawn threads that go and
do
jobs at the same time as the one that spawned it. You have learned how
to send simple messages over a network in a client-server model, using
Socket and ServerSocket. You have also learned how to use threading to
improve the client and the server of your application.
<<
Back to contents
page author: Andrew Chinery
last updated: 01 March 2013