// This example is from the book _Java Threads_ by Scott Oaks and Henry Wong.
// Written by Scott Oaks and Henry Wong.
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
// Sample TCPServer -- Chapter 5, p. 93. This is a fully functional example;
// see also the TCPServer in chapter 8 which runs each client in a separate
// thread group.
import java.net.*;
import java.io.*;
public class TCPServer implements Cloneable, Runnable {
Thread runner = null;
ServerSocket server = null;
Socket data = null;
public synchronized void startServer(int port) throws IOException {
if (runner == null) {
server = new ServerSocket(port);
runner = new Thread(this);
runner.start();
}
}
public synchronized void stopServer() {
if (server != null) {
runner.stop();
runner == null;
server.close();
}
}
public void run() {
if (server != null) {
while (true) {
try {
Socket datasocket = server.accept();
TCPServer newSocket = (TCPServer) clone();
newSocket.server = null;
newSocket.data = datasocket;
newSocket.runner = new Thread(newSocket);
newSocket.runner.start();
} catch (Exception e) {}
}
} else {
run(data);
}
}
public void run(Socket data) {
}
}
|