03.bio基本实现02

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的连接请求
            while(true){
                //3. 开始监听客户端的Socket连接请求
                Socket socket = ss.accept();
                //4. 创建线程处理与客户端socket通信
                new ServerThreadReader(socket).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//线程对象
public class ServerThreadReader extends Thread {
    private Socket socket;

    public ServerThreadReader(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 1.从socket的管道中得到字节输入流
            InputStream is = socket.getInputStream();
            // 2.把字节输入流包装成缓存字符输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String msg;
            while ((msg = br.readLine()) != null){
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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