001    package org.crsh.util;
002    
003    import java.io.Closeable;
004    import java.io.IOException;
005    import java.io.InputStream;
006    import java.io.OutputStream;
007    import java.net.InetSocketAddress;
008    import java.net.ServerSocket;
009    import java.net.Socket;
010    
011    /** @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a> */
012    public abstract class AbstractSocketServer implements Closeable {
013    
014      /** . */
015      private final int bindingPort;
016    
017      /** . */
018      private ServerSocket socketServer;
019    
020      /** . */
021      private Socket socket;
022    
023      /** . */
024      private InputStream in;
025    
026      /** . */
027      private OutputStream out;
028    
029      /** . */
030      private int port;
031    
032      public AbstractSocketServer(int bindingPort) {
033        this.bindingPort = bindingPort;
034      }
035    
036      public final int getBindingPort() {
037        return socketServer.getLocalPort();
038      }
039    
040      public final int getPort() {
041        return port;
042      }
043    
044      public final int bind() throws IOException {
045        ServerSocket socketServer = new ServerSocket();
046        socketServer.bind(new InetSocketAddress(bindingPort));
047        int port = socketServer.getLocalPort();
048    
049        //
050        this.socketServer = socketServer;
051        this.port = port;
052    
053        //
054        return port;
055      }
056    
057      public final void accept() throws IOException {
058        if (socketServer == null) {
059          throw new IllegalStateException();
060        }
061    
062        //
063        this.socket = socketServer.accept();
064        this.in = socket.getInputStream();
065        this.out = socket.getOutputStream();
066    
067        //
068        handle(in, out);
069      }
070    
071      protected abstract void handle(InputStream in, OutputStream out) throws IOException;
072    
073      public final void close() {
074        try {
075          Safe.close(socket);
076          Safe.close(in);
077          Safe.close(out);
078        }
079        finally {
080          this.socket = null;
081          this.in = null;
082          this.out = null;
083        }
084      }
085    }