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