IO鐢ㄦ硶鍑犱緥

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IO鐢ㄦ硶鍑犱緥相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/http' title='http'>http   each   soc   alt   string   puts   闃诲   catch   info   

涓€涓緥瀛?/p>

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();
        }
    }
}

绾跨▼鍚姩

姣忎釜閮藉紑涓€涓嚎绋嬭繃浜庢氮璐癸紝绾跨▼姹犳敼杩?/p>

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

鎶€鏈浘鐗? src=

 

骞跺彂閲忎笉澶х殑鎯呭喌杩欑鍚屾闃诲鏂瑰紡鏄彲浠ョ殑锛屼絾鏄敱浜庣嚎绋嬬殑涓婁笅鏂囧垏鎹㈡槸搴熸€ц兘鐨勶紝鍦ㄩ珮骞跺彂鎯呭喌涓嬫樉鐒朵笉鍚堥€傘€?/p>

 

锛堝緟琛ュ厖锛?/p>

以上是关于IO鐢ㄦ硶鍑犱緥的主要内容,如果未能解决你的问题,请参考以下文章

QMessageBox 涓昏鐢ㄦ硶

axios鎷︽埅鍣ㄧ殑鐢ㄦ硶

vi | vim 鐢ㄦ硶

鎶撳寘宸ュ叿 tcpdump 鐢ㄦ硶璇存槑

鐩掑瓙妯″瀷 box-sizing 鐢ㄦ硶

杩唬鍣ㄥ拰鐢熸垚鍣ㄧ殑鐢ㄦ硶