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.Socket; 009 010 /** @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a> */ 011 public abstract class AbstractSocketClient implements Closeable { 012 013 /** . */ 014 private int port; 015 016 /** . */ 017 private Socket socket; 018 019 /** . */ 020 private InputStream in; 021 022 /** . */ 023 private OutputStream out; 024 025 public AbstractSocketClient(int port) { 026 this.port = port; 027 } 028 029 public final void connect() throws IOException { 030 Socket socket = new Socket(); 031 socket.connect(new InetSocketAddress(port)); 032 InputStream in = socket.getInputStream(); 033 OutputStream out = socket.getOutputStream(); 034 035 // 036 this.socket = socket; 037 this.in = in; 038 this.out = out; 039 040 // 041 handle(in ,out); 042 } 043 044 protected abstract void handle(InputStream in, OutputStream out) throws IOException; 045 046 public final void close() { 047 try { 048 Safe.close(socket); 049 Safe.close(in); 050 Safe.close(out); 051 } 052 finally { 053 this.socket = null; 054 this.in = null; 055 this.out = null; 056 } 057 } 058 }