NetworkServer.java revision 12745:f068a4ffddd2
1/*
2 * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25package sun.net;
26
27import java.io.*;
28import java.net.Socket;
29import java.net.ServerSocket;
30import sun.misc.ManagedLocalsThread;
31
32/**
33 * This is the base class for network servers.  To define a new type
34 * of server define a new subclass of NetworkServer with a serviceRequest
35 * method that services one request.  Start the server by executing:
36 * <pre>
37 *      new MyServerClass().startServer(port);
38 * </pre>
39 */
40public class NetworkServer implements Runnable, Cloneable {
41    /** Socket for communicating with client. */
42    public Socket clientSocket = null;
43    private Thread serverInstance;
44    private ServerSocket serverSocket;
45
46    /** Stream for printing to the client. */
47    public PrintStream clientOutput;
48
49    /** Buffered stream for reading replies from client. */
50    public InputStream clientInput;
51
52    /** Close an open connection to the client. */
53    public void close() throws IOException {
54        clientSocket.close();
55        clientSocket = null;
56        clientInput = null;
57        clientOutput = null;
58    }
59
60    /** Return client connection status */
61    public boolean clientIsOpen() {
62        return clientSocket != null;
63    }
64
65    public final void run() {
66        if (serverSocket != null) {
67            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
68            // System.out.print("Server starts " + serverSocket + "\n");
69            while (true) {
70                try {
71                    Socket ns = serverSocket.accept();
72//                  System.out.print("New connection " + ns + "\n");
73                    NetworkServer n = (NetworkServer)clone();
74                    n.serverSocket = null;
75                    n.clientSocket = ns;
76                    new ManagedLocalsThread(n).start();
77                } catch(Exception e) {
78                    System.out.print("Server failure\n");
79                    e.printStackTrace();
80                    try {
81                        serverSocket.close();
82                    } catch(IOException e2) {}
83                    System.out.print("cs="+serverSocket+"\n");
84                    break;
85                }
86            }
87//          close();
88        } else {
89            try {
90                clientOutput = new PrintStream(
91                        new BufferedOutputStream(clientSocket.getOutputStream()),
92                                               false, "ISO8859_1");
93                clientInput = new BufferedInputStream(clientSocket.getInputStream());
94                serviceRequest();
95                // System.out.print("Service handler exits
96                // "+clientSocket+"\n");
97            } catch(Exception e) {
98                // System.out.print("Service handler failure\n");
99                // e.printStackTrace();
100            }
101            try {
102                close();
103            } catch(IOException e2) {}
104        }
105    }
106
107    /** Start a server on port <i>port</i>.  It will call serviceRequest()
108        for each new connection. */
109    public final void startServer(int port) throws IOException {
110        serverSocket = new ServerSocket(port, 50);
111        serverInstance = new ManagedLocalsThread(this);
112        serverInstance.start();
113    }
114
115    /** Service one request.  It is invoked with the clientInput and
116        clientOutput streams initialized.  This method handles one client
117        connection. When it is done, it can simply exit. The default
118        server just echoes it's input. It is invoked in it's own private
119        thread. */
120    public void serviceRequest() throws IOException {
121        byte buf[] = new byte[300];
122        int n;
123        clientOutput.print("Echo server " + getClass().getName() + "\n");
124        clientOutput.flush();
125        while ((n = clientInput.read(buf, 0, buf.length)) >= 0) {
126            clientOutput.write(buf, 0, n);
127        }
128    }
129
130    public static void main(String argv[]) {
131        try {
132            new NetworkServer ().startServer(8888);
133        } catch (IOException e) {
134            System.out.print("Server failed: "+e+"\n");
135        }
136    }
137
138    /**
139     * Clone this object;
140     */
141    public Object clone() {
142        try {
143            return super.clone();
144        } catch (CloneNotSupportedException e) {
145            // this shouldn't happen, since we are Cloneable
146            throw new InternalError(e);
147        }
148    }
149
150    public NetworkServer () {
151    }
152}
153