日期:2014-05-20 浏览次数:20764 次
import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public abstract class SocketServer implements Runnable { public static void main(String[] args) throws Exception { SocketServer server = new SocketServer(4321) { @Override protected void serve(Socket socket) { try { PrintStream ps = new PrintStream(socket.getOutputStream()); ps.println("Hello!"); ps.flush(); ps.close(); socket.close(); } catch(IOException ex) { ex.printStackTrace(); } } }; server.start(); // ... } private final int port; private volatile boolean runFlag; private ExecutorService executor; public SocketServer(int port) { this.port = port; } @Override public void run() { ServerSocket ss = null; try { ss = new ServerSocket(port); runFlag = true; while( runFlag ) { Socket socket = ss.accept(); if( runFlag ) getExecutor().submit(new Connection(socket)); } } catch(IOException ex) { throw new RuntimeException(ex); } finally { try { if( ss != null ) ss.close(); } catch(Exception e) { // log exception } } } public void start() { getExecutor().submit(this); } public void stop() { runFlag = false; try { new Socket("127.0.0.1", port).close(); } catch(IOException ex) { // not important } } protected abstract void serve(Socket socket); protected ExecutorService getExecutor() { if( executor == null ) executor = Executors.newCachedThreadPool(); return executor; } private class Connection implements Runnable { private final Socket socket; private Connection(Socket socket) { this.socket = socket; } @Override public void run() { serve(socket); } } }
------解决方案--------------------
先去了解下阻塞式IO和异步式IO(NIO)