yls 2020/5/23java
/** * BIO Socket通訊實例 */ public class BioServer { public static void main(String[] args) throws IOException { ExecutorService threadPool = Executors.newCachedThreadPool(); //建立serverSocket,並綁定端口 //構造函數內部與 serverSocket.bind(new InetSocketAddress("localhost",6666)); 實現一致 ServerSocket serverSocket = new ServerSocket(6666); while (true) { //監聽,等待客戶端鏈接 Socket socket = serverSocket.accept(); System.out.println("鏈接到一個客戶端"); System.out.println(socket.getPort()); System.out.println(socket.getInetAddress()); //接收到客戶端後,就啓動一個新線程,否則其它後進來的線程沒法鏈接 threadPool.execute(() -> { try ( //獲取socket 輸入流,用來接收數據,不阻塞 InputStream inputStream = socket.getInputStream(); ////獲取socket 輸出流流,用來發送數據,不阻塞 OutputStream outputStream = socket.getOutputStream() ) { System.out.println("獲取socket 輸入流成功。。。"); while (true) { byte[] bytes = new byte[2]; //阻塞 int read = inputStream.read(bytes); System.out.println("read======" + read); System.out.println("從輸入流獲取值成功。。。"); System.out.println(new String(bytes, 0, read)); //向客戶端發送數據 outputStream.write("22222......".getBytes()); outputStream.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("finally 執行了。。。"); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }); } } }
public class BioClient { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try ( //鏈接服務端 Socket socket = new Socket("127.0.0.1", 6999); //獲取socket輸出流,用於發數據 OutputStream outputStream = socket.getOutputStream(); //獲取socket輸入流,用於接收數據 InputStream inputStream = socket.getInputStream() ) { System.out.println("鏈接服務端成功。。。。。"); while (true) { //發數據 outputStream.write(scanner.nextLine().getBytes()); System.out.println("發送數據成功。。。。"); byte[] bytes = new byte[128]; //接收數據 while (true) { int read = inputStream.read(bytes); if (read == -1) break; System.out.println("接收數據成功"); System.out.println(new String(bytes, 0, read)); } } } catch (IOException e) { e.printStackTrace(); } finally { } } }