IO用法几例

一个例子

public class DemoServer extends Thread {
    private ServerSocket serverSocket;

    public int getPort() {
        return serverSocket.getLocalPort();
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(0);    // 绑定0端口
            while (true) {
                Socket socket = serverSocket.accept();      // 调用accept方法,阻塞等待客户端连接
                RequestHandler requestHandler = new RequestHandler(socket);
                requestHandler.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        DemoServer server = new DemoServer();
        server.start();        
        try (Socket client = new Socket(InetAddress.getLocalHost(), server.getPort())) {    // 模拟socket客户端
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            bufferedReader.lines().forEach(s -> System.out.println(s));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class RequestHandler extends Thread {
    private Socket socket;
    RequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (PrintWriter out = new PrintWriter(socket.getOutputStream());) {
            out.println("hello");
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

线程启动

每个都开一个线程过于浪费,线程池改进

            serverSocket = new ServerSocket(0);
            executorService = Executors.newFixedThreadPool(8);
            while (true) {
                Socket socket = serverSocket.accept();
                RequestHandler requestHandler = new RequestHandler(socket);
//                requestHandler.start();
                executorService.execute(requestHandler);
            }

IO用法几例

 

并发量不大的情况这种同步阻塞方式是可以的,但是由于线程的上下文切换是废性能的,在高并发情况下显然不合适。

 

(待补充)

上一篇:Tornado RequestHandler包含的方法


下一篇:MSF常用命令