Examen Java
Examen Java
Examen Java
Learn Java #4
Fall 2006
Learn Java #4
3. Add Java Threads to Server: You are to redo the server application in the above to allow several clients
to connect to the server at one time. There is no need for you to modify your client application.
In your new server, you will need to create a new Java thread for each client. Full details of Java
threads are covered in Chapter 23 of Java text. However, you dont need to understand all the ins and
outs of Java threads to do this exercise.
Use the following code as a model. Study it carefully.
// a Java
// By Dan
import
import
public
Learn Java #4
}
}
public void run() {
// Assumes client sends a string, receives a string response
// then quits.
String lineIn = "";
try {
// must cast from Object to String
lineIn = (String) in.readObject();
System.out.println( "Received from " +
clientSocket.getInetAddress().getHostName() +
": " + lineIn );
// important to create a new object in this case a String
out.writeObject(new String( "WOW! " + lineIn ) );
}
catch ( ClassNotFoundException e ){
System.err.println( "Class not found " + e );
System.exit(0);
}
catch ( IOException e2 ){
System.err.println( "Error in I/O " + e2 );
System.exit(0);
}
// close client
try {
in.close();
out.close();
clientSocket.close();
System.out.println( "Connection closed from " +
clientSocket.getInetAddress().getHostName() );
}
catch ( IOException e3 ){
System.err.println( "Error 2 in connection " + e3 );
System.exit(0);
}
}
}
One way to create threads is to have a class that extends Thread. Any class that extends the class
Thread must have a public void run() method. You start the thread by calling the start()
method of the super class Thread which calls your run() method.
The idea of the exercsie is to have separate threads that continue to process existing clients while the
server waits for requests from new clients. When the server accepts a new client, the server creates a
new thread to handle it and goes back to waiting for a new client.
Using Java threads for your server is relatively easy because the different threads do not share information nor need to coordinate between themselves. Having a server spawn a new thread (or process)
for each new client is very common in client/server applications.
Learn Java #4