From 9f9adf8ab272410b37059336c804b689ca555b17 Mon Sep 17 00:00:00 2001 From: bingor Date: Sat, 6 May 2023 10:20:12 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=BC=96=E7=A8=8B=E5=9F=BA?= =?UTF-8?q?=E7=A1=80-BIO-=E7=BB=83=E4=B9=A0=EF=BC=88=E5=AF=B9=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E8=BF=9B=E8=A1=8C=E4=BC=98=E5=8C=96=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/msb/io/bio/BioClient.java | 4 +- src/main/java/com/msb/io/bio/BioServer.java | 56 ++++++++++++++++----- 2 files changed, 44 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/msb/io/bio/BioClient.java b/src/main/java/com/msb/io/bio/BioClient.java index 2ce029e..019b77e 100644 --- a/src/main/java/com/msb/io/bio/BioClient.java +++ b/src/main/java/com/msb/io/bio/BioClient.java @@ -1,7 +1,5 @@ package com.msb.io.bio; -import jdk.internal.util.xml.impl.Input; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -24,7 +22,7 @@ public class BioClient { try { socket = new Socket("127.0.0.1", 8888); outputStream = socket.getOutputStream(); - outputStream.write("服务端,你好,我是小袁".getBytes()); + outputStream.write("服务端,你好,我是小斌".getBytes()); byte [] bytes = new byte[1024]; inputStream = socket.getInputStream(); diff --git a/src/main/java/com/msb/io/bio/BioServer.java b/src/main/java/com/msb/io/bio/BioServer.java index 77f1753..876c40b 100644 --- a/src/main/java/com/msb/io/bio/BioServer.java +++ b/src/main/java/com/msb/io/bio/BioServer.java @@ -26,19 +26,9 @@ public class BioServer { while (true) { Socket socket = serverSocket.accept(); - InputStream inputStream = socket.getInputStream(); - byte[] bytes = new byte[1024]; - int len = inputStream.read(bytes); - String msg = new String(bytes, 0, len); - System.out.println("服务端接收到客户端的信息:" + msg); - - OutputStream outputStream = socket.getOutputStream(); - outputStream.write("客户端,你好!".getBytes()); - outputStream.flush(); - - outputStream.close(); - inputStream.close(); - socket.close(); + new Thread(() -> { + handle(socket); + }).start(); } } catch (IOException e) { @@ -57,4 +47,44 @@ public class BioServer { } + public static void handle(Socket socket) { + + InputStream inputStream = null; + OutputStream outputStream = null; + + try { + inputStream = socket.getInputStream(); + byte[] bytes = new byte[1024]; + int len = inputStream.read(bytes); + String msg = new String(bytes, 0, len); + System.out.println("服务端接收到客户端的信息:" + msg); + + outputStream = socket.getOutputStream(); + outputStream.write("客户端,你好!".getBytes()); + outputStream.flush(); + + } catch (IOException exception) { + exception.printStackTrace(); + } finally { + + try { + if(outputStream != null) { + outputStream.close(); + } + if(inputStream != null) { + inputStream.close(); + } + if(socket != null) { + socket.close(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + + } + + + + } + }