upstream version 1.2.2
[debian/freetts] / demo / util / TTSServer.java
1 /**
2  * Copyright 2001 Sun Microsystems, Inc.
3  * 
4  * See the file "license.terms" for information on usage and
5  * redistribution of this file, and for a DISCLAIMER OF ALL 
6  * WARRANTIES.
7  */
8 import java.io.IOException;
9 import java.net.ServerSocket;
10 import java.net.Socket;
11
12
13 /**
14  * A bare-bones Server containing a ServerSocket waiting for connection
15  * requests. Subclasses should implement the <code>spawnProtocolHandler</code>
16  * method.
17  */
18 public abstract class TTSServer implements Runnable {
19
20     /**
21      * The port number to listen on. It is the value specified by the
22      * System property "port".
23      */
24     protected int port = Integer.parseInt
25         (System.getProperty("port", String.valueOf(2222)));
26
27
28     /**
29      * Implements the run() method of Runnable interface. It starts a
30      * ServerSocket, listens for connections, and spawns a handler for
31      * each connection.
32      */
33     public void run() {
34         ServerSocket ss;
35
36         try {
37             ss = new ServerSocket(port);
38             System.out.println("Waiting on " + ss);
39         } catch (IOException ioe) {
40             System.out.println("Can't open socket on port " + port);
41             ioe.printStackTrace();
42             return;
43         }
44
45         while (true) {
46             try {
47                 Socket socket = ss.accept();
48                 System.out.println("... new socket connection");
49                 spawnProtocolHandler(socket);
50             } catch (IOException ioe) {
51                 System.err.println("Could not accept socket " + ioe);
52                 ioe.printStackTrace();
53                 break;
54             }
55         }
56
57         try {
58             ss.close();
59         } catch (IOException ioe) {
60             System.err.println("Could not close server socket " + ioe);
61             ioe.printStackTrace();
62         }
63     }
64
65
66     /**
67      * This method is called after a connection request is made to this
68      * TTSServer. The <code>Socket</code> created as a result of the
69      * connection request is passed to this method.
70      *
71      * @param socket the socket
72      */
73     protected abstract void spawnProtocolHandler(Socket socket);
74 }