commit 4d810fc5b9659f606088c60a487cba0861d85e7d Author: bingor Date: Wed Oct 19 18:08:34 2022 +0800 网络编程基础-bio diff --git a/src/main/java/com/msb/io/bio/Client.java b/src/main/java/com/msb/io/bio/Client.java new file mode 100644 index 0000000..ee260da --- /dev/null +++ b/src/main/java/com/msb/io/bio/Client.java @@ -0,0 +1,35 @@ +package com.msb.io.bio;/** + * @Author bingor + * @Date 2022/10/19 14:59 + * @Description: com.msb.bio + * @Version: 1.0 + */ + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; + +/** + *@ClassName Client + *@Description TODO + *@Author bingor + *@Date 2022/10/19 14:59 + *@Version 3.0 + */ +public class Client { + public static void main(String[] args) { + try { + Socket socket = new Socket("127.0.0.1", 8888); + OutputStream os = socket.getOutputStream(); + os.write("hello server".getBytes()); + os.flush(); + System.out.println("write over, waiting for msg back..."); + byte[] bytes = new byte[1024]; + int len = socket.getInputStream().read(bytes); + System.out.println(new String(bytes, 0, len)); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/msb/io/bio/Server.java b/src/main/java/com/msb/io/bio/Server.java new file mode 100644 index 0000000..58368ea --- /dev/null +++ b/src/main/java/com/msb/io/bio/Server.java @@ -0,0 +1,49 @@ +package com.msb.io.bio;/** + * @Author bingor + * @Date 2022/10/19 15:11 + * @Description: com.msb.bio + * @Version: 1.0 + */ + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; + +/** + *@ClassName Server + *@Description TODO + *@Author bingor + *@Date 2022/10/19 15:11 + *@Version 3.0 + */ +public class Server { + public static void main(String[] args) { + try { + ServerSocket server = new ServerSocket(); + server.bind(new InetSocketAddress("127.0.0.1", 8888)); + while (true) { + Socket socket = server.accept(); //阻塞方法 + + new Thread(() -> { + handle(socket); + }).start(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void handle(Socket socket) { + byte[] bytes = new byte[1024]; + try { + int len = socket.getInputStream().read(bytes); + System.out.println(new String(bytes, 0, len)); + + socket.getOutputStream().write("hello client".getBytes()); + socket.getOutputStream().flush(); + } catch (IOException e) { + e.printStackTrace(); + } + } +}