1. 程式人生 > >java IO(BIO)、NIO、AIO

java IO(BIO)、NIO、AIO

.get ati NPU read end get dex 你好 nts

IO

服務端ServerSocket 客戶端Socket

缺點每次客戶端建立連接都會另外啟一個線程處理。讀取和發送數據都是阻塞式的。

如果1000個客戶端建立連接將會產生1000個線程

Server端

package bhz.bio.test;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


public class Server {
    private int port;
    private ServerSocket serverSocket;

    
public Server(int port) { this.port = port; } public void start() throws IOException { try { serverSocket = new ServerSocket(port); while (true) { Socket socket = serverSocket.accept();// 阻塞等待客戶端建立連接 new Thread(new
ServerHandler(socket)).start();//另外起一個線程處理客戶端的請求 } } catch (IOException e) { e.printStackTrace(); // TODO Auto-generated catch block System.out.println("服務器啟動失敗"); }finally { if(serverSocket!=null) { serverSocket.close();
//釋放資源操作 }

} } }

ServerHandler

package bhz.bio.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerHandler implements Runnable {
    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

        BufferedReader in = null;
        PrintWriter out = null;
        try {
            while (true) {
                // 監聽客戶端的發送消息
                out = new PrintWriter(socket.getOutputStream(),true); 
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String content = in.readLine();
                
                System.out.println("接收到客戶端發送的消息:" + content);//
                out.println("哈哈哈");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            socket = null;
        }

    }

}

客戶端

package bhz.bio.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    private String ip;
    private int port;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    public Client(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void connect() {
        try {
            socket = new Socket(ip, port);
            out = new PrintWriter(socket.getOutputStream(),true); 
            in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("建立連接失敗");
        }

    }
    
    public void send(String message) throws IOException {
        
         out.println(message);
         
         try {
             String content=in.readLine();
               System.out.println("接收到服務端的數據:"+content);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
      
         
    }
}

測試類

package bhz.bio.test;

import java.io.IOException;

public class mainTest {
  public static void main(String[] args) {
      //啟動服務端
    new Thread(new Runnable() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Server server=new Server(8089);
            try {
                server.start();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }).start();

    new Thread(new Runnable() {
        
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Client client=new Client("127.0.0.1", 8089);
            client.connect();//與服務器建立連接
            try {
                client.send("你好呀");
                client.send("你好呀2");
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }).start();
}
}

輸出

接收到客戶端發送的消息:你好呀
接收到服務端的數據:哈哈哈
接收到客戶端發送的消息:你好呀2
接收到服務端的數據:哈哈哈

使用線程池限制客戶端數量(偽異步)

ServerHandler修改

package bhz.bio.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerHandler implements Runnable {
    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

        BufferedReader in = null;
        PrintWriter out = null;
        try {
            while (true) {
                // 監聽客戶端的發送消息
                out = new PrintWriter(socket.getOutputStream(),true); 
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String content = in.readLine();
                
                System.out.println("接收到客戶端發送的消息:" + content);//
                out.println("哈哈哈");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            socket = null;
        }

    }

}

當使用正在連接的客戶端超過50個過後 阻塞

java IO(BIO)、NIO、AIO