BIO 与 NIO 之 Socket

简单的客户端给服务端发送数据:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Created by Administrator on 2017/7/12.
 */
public class BIOTest {
    public static void main(String[] args) {
        Thread server = new Thread(new Server());
        server.start();
        Thread client = new Thread(new Client());
        client.start();

    }

    static class Server implements Runnable {
        @Override
        public void run() {
            ServerSocket serverSocket = null;
            SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 9999);
            try {
                serverSocket = new ServerSocket();
                serverSocket.bind(socketAddress);
                System.out.println("Server:accept");
                Socket socket = serverSocket.accept();
                try {
                    BufferedReader buf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    System.out.println("Server:while");
                    while (true) {
                        System.out.println("Server:readLine");
                        String str = buf.readLine();
                        System.out.println("Server:====" + str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class Client implements Runnable {
        @Override
        public void run() {
            try {
                Socket client = new Socket("127.0.0.1", 9999);
                BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                PrintStream out = new PrintStream(client.getOutputStream());
                while (true) {
                    System.out.println("Client:readLine");
                    String str = input.readLine();
                    if (str.equals("Q"))
                        break;
                    //发送数据到服务端
                    out.println(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

accept、readLine都是阻塞的:

1、Socket socket = serverSocket.accept();

这里服务端等待客户端连接,一直没有客户端连接是不会往下走的。

2、String str = buf.readLine();

客户端连上之后,服务端不停的从流里面读数据,但是这里也是阻塞的,如果客户端一直不发数据也不会进入下一次循环。

3、String str = input.readLine();

客户端读取控制台输入也是阻塞的。

这里就能看到相比于NIO,等待消息时间+处理消息时间 等待消息时间什么事情都没有做,CPU空闲,但是当前线程是什么都干不了的。只能用多线程来充分利用CPU。

# NIO 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×