CM10228 / Programming Ib:   Lab 2

Concurrency and Networking: Concurrency Meets Networking

<< Back to contents

In this section we are going to show you how to improve your client and your server using threads. If you read ahead on the Oracle tutorial, then you will have seen that in order to support multiple clients in Java you will need threads on the server side. This is true! It may be less obvious that you also need threads on the client side, but you do. This is so you can receive an unspecified number of lines from the server much more easily. As you are about to find out.

Client Threading

Do this:

Run your client with the new server. What do you notice? Chances are that you only receive one line, i.e. one character, of the response. The reason for this is because you only read one line from the server for every line that is sent. Now, you might be tempted to put the call to a read line from the server in a loop and just read as many as it sends back. However, the method call to read a line will actually wait for a response. Therefore if you try to read lines until the server stops sending them, you will find that your program will hang, as eventually it will stop but your program will keep waiting.

The way we will solve this is to introduce threads into the client. The idea is as follows:

Do this:

Now your client can listen to the server and send more lines at the same time, no matter how many lines the server sends or how much input the user gives.

Server Threading

If you haven't already, read the final section of the networking tutorial at the bottom of the page called Supporting Multiple Clients. The basic idea with multiple clients is that on the server side your main thread listens for new connections, creates a thread to deal with it when one comes in, and then goes back to listening for new connections.

Do this:

Now you should have two threaded applications, one client and one server. The server should be able to support multiple clients which should be able to support multiple lines coming back form the server. It's time to move to the chat application and the final stage of this sheet.

Chat application >>



page author: Andrew Chinery
last updated: 01 March 2013