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  */
  25 package sun.net;
  26 
  27 import java.io.*;
  28 import java.net.Socket;
  29 import java.net.ServerSocket;
  30 
  31 /**
  32  * This is the base class for network servers.  To define a new type
  33  * of server define a new subclass of NetworkServer with a serviceRequest
  34  * method that services one request.  Start the server by executing:
  35  * <pre>
  36  *      new MyServerClass().startServer(port);
  37  * </pre>
  38  */
  39 public class NetworkServer implements Runnable, Cloneable {
  40     /** Socket for communicating with client. */
  41     public Socket clientSocket = null;
  42     private Thread serverInstance;
  43     private ServerSocket serverSocket;
  44 
  45     /** Stream for printing to the client. */
  46     public PrintStream clientOutput;
  47 
  48     /** Buffered stream for reading replies from client. */
  49     public InputStream clientInput;
  50 
  51     /** Close an open connection to the client. */
  52     public void close() throws IOException {
  53         clientSocket.close();
  54         clientSocket = null;
  55         clientInput = null;
  56         clientOutput = null;
  57     }
  58 
  59     /** Return client connection status */
  60     public boolean clientIsOpen() {
  61         return clientSocket != null;
  62     }
  63 
  64     public final void run() {
  65         if (serverSocket != null) {
  66             Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
  67             // System.out.print("Server starts " + serverSocket + "\n");
  68             while (true) {
  69                 try {
  70                     Socket ns = serverSocket.accept();
  71 //                  System.out.print("New connection " + ns + "\n");
  72                     NetworkServer n = (NetworkServer)clone();
  73                     n.serverSocket = null;
  74                     n.clientSocket = ns;
  75                     new Thread(null, n, "NetworkServer", 0, false).start();
  76                 } catch(Exception e) {
  77                     System.out.print("Server failure\n");
  78                     e.printStackTrace();
  79                     try {
  80                         serverSocket.close();
  81                     } catch(IOException e2) {}
  82                     System.out.print("cs="+serverSocket+"\n");
  83                     break;
  84                 }
  85             }
  86 //          close();
  87         } else {
  88             try {
  89                 clientOutput = new PrintStream(
  90                         new BufferedOutputStream(clientSocket.getOutputStream()),
  91                                                false, "ISO8859_1");
  92                 clientInput = new BufferedInputStream(clientSocket.getInputStream());
  93                 serviceRequest();
  94                 // System.out.print("Service handler exits
  95                 // "+clientSocket+"\n");
  96             } catch(Exception e) {
  97                 // System.out.print("Service handler failure\n");
  98                 // e.printStackTrace();
  99             }
 100             try {
 101                 close();
 102             } catch(IOException e2) {}
 103         }
 104     }
 105 
 106     /** Start a server on port <i>port</i>.  It will call serviceRequest()
 107         for each new connection. */
 108     public final void startServer(int port) throws IOException {
 109         serverSocket = new ServerSocket(port, 50);
 110         serverInstance = new Thread(null, this, "NetworkServer", 0, false);
 111         serverInstance.start();
 112     }
 113 
 114     /** Service one request.  It is invoked with the clientInput and
 115         clientOutput streams initialized.  This method handles one client
 116         connection. When it is done, it can simply exit. The default
 117         server just echoes it's input. It is invoked in it's own private
 118         thread. */
 119     public void serviceRequest() throws IOException {
 120         byte buf[] = new byte[300];
 121         int n;
 122         clientOutput.print("Echo server " + getClass().getName() + "\n");
 123         clientOutput.flush();
 124         while ((n = clientInput.read(buf, 0, buf.length)) >= 0) {
 125             clientOutput.write(buf, 0, n);
 126         }
 127     }
 128 
 129     public static void main(String argv[]) {
 130         try {
 131             new NetworkServer ().startServer(8888);
 132         } catch (IOException e) {
 133             System.out.print("Server failed: "+e+"\n");
 134         }
 135     }
 136 
 137     /**
 138      * Clone this object;
 139      */
 140     public Object clone() {
 141         try {
 142             return super.clone();
 143         } catch (CloneNotSupportedException e) {
 144             // this shouldn't happen, since we are Cloneable
 145             throw new InternalError(e);
 146         }
 147     }
 148 
 149     public NetworkServer () {
 150     }
 151 }