02.bio基本实现01

01.BIO实现

一个客户端发消息、一个服务端收消息

//客户端
public class Client {
    public static void main(String[] args) {
        try {
            //1. 创建Socket对象请求服务端的连接
            Socket socket = new Socket("127.0.0.1",9999);
            //2. 从Socket对象获取一个字节输出流
            OutputStream os = socket.getOutputStream();
            //3. 把字节输出流包装成一个打印流
            PrintStream ps = new PrintStream(os);
            Scanner sc = new Scanner(System.in);
            while (true){
                System.out.print("请说:");
                String msg = sc.nextLine();
                ps.println(msg);
                ps.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//服务端
public class Server {
    public static void main(String[] args) {
        try {
            //1. 服务端端口注册:(ServerSocket)
            ServerSocket ss = new ServerSocket(9999);
            //2. 开始监听客户端的Socket连接请求
            Socket socket = ss.accept();
            //3. 从socket的管道中得到字节输入流
            InputStream is = socket.getInputStream();
            //4. 把字节输入流包装成缓存字符输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String msg;
            while ((msg = br.readLine()) != null){
                System.out.println("服务端接收到:" + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(02.bio基本实现01)