import java.io.*; import java.net.*; public class Server extends Thread { ClientHandlerFactory chf; ServerSocket ss; public Server(int port, ClientHandlerFactory chf) { this.chf = chf; try { ss = new ServerSocket(port); } catch (Exception e) { e.printStackTrace(); } } public void run() { while (true) { try { Socket s = ss.accept(); ServerBehavior sb = chf.getNewClientHandler(); sb.setStreams(s.getOutputStream(), s.getInputStream()); sb.setSocket(s); (new Thread(sb)).start(); } catch (Exception e) { e.printStackTrace(); } } } // creates the objects that communicate with clients public interface ClientHandlerFactory { public ServerBehavior getNewClientHandler(); } // for defining how the server talks to clients public static interface ServerBehavior extends Runnable { public void setStreams(OutputStream os, InputStream is); public void setSocket(Socket s); public void closeSocket(); } // just for convenience... public static class ServerBehaviorAdapter implements ServerBehavior { protected OutputStream os; protected InputStream is; protected Socket socket; public void setStreams(OutputStream os, InputStream is) { this.os = os; this.is = is; } public void setSocket(Socket s) { socket = s; } public void closeSocket() { try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } public void run() { } } }