码迷,mamicode.com
首页 > 其他好文 > 详细

IO用法几例

时间:2020-01-09 13:10:33      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:http   each   soc   alt   string   puts   阻塞   catch   info   

一个例子

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用法几例

标签:http   each   soc   alt   string   puts   阻塞   catch   info   

原文地址:https://www.cnblogs.com/CherryTab/p/12170855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!