Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
16.12 A Debugging Web Server
427
Listing 16.9 EchoServer.java (continued)
private int getLength(String length) {
StringTokenizer tok = new StringTokenizer(length);
tok.nextToken();
return(Integer.parseInt(tok.nextToken()));
}
}
ThreadedEchoServer
Listing 16.10 presents a multithreaded variation of the
EchoServer
, useful
when your server needs to accept multiple simultaneous client requests.
Listing 16.10 ThreadedEchoServer.java
import java.net.*;
import java.io.*;
/** A multithreaded variation of EchoServer. */
public class ThreadedEchoServer extends EchoServer
implements Runnable {
public static void main(String[] args) {
int port = 8088;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch(NumberFormatException nfe) {}
}
ThreadedEchoServer echoServer =
new ThreadedEchoServer(port, 0);
echoServer.serverName = "Threaded Echo Server";
}
public ThreadedEchoServer(int port, int connections) {
super(port, connections);
}
/** The new version of handleConnection starts
* a thread. This new thread will call back to the
* old version of handleConnection, resulting
* in the same server behavior in a multithreaded
* version. The thread stores the Socket instance
* since run doesn't take any arguments, and since
* storing the socket in an instance variable risks
* having it overwritten if the next thread starts
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved