3、java.nio、ServerSocketChannel SocketChannel 堵塞模式使用

public static void main(String[] args) throws Exception {
    // 服务端
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    // 设置为堵塞模式
    serverSocketChannel.configureBlocking(true);
    // 绑定本地ip端口
    serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8080));
    // 堵塞模式下没有连接会一直堵塞在下面这句accept
    SocketChannel socketChannel = serverSocketChannel.accept();
    // 有连接进来了,正常使用方式是创建一个线程 socketChannel 作为参数传入,demo就简单写一下
    socketChannel.write(ByteBuffer.wrap("你好客户端".getBytes()));
    socketChannel.close();
    serverSocketChannel.close();
  }
public static void main(String[] args) throws Exception {
    // 客户端
    SocketChannel socketChannel = SocketChannel.open();
    // 设置为堵塞模式
    socketChannel.configureBlocking(true);
    // 连接远程ip+端口 因为设置了堵塞模式没连上服务器就会一直堵塞
    socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    // 接收服务器传来的字节集
    int i = socketChannel.read(byteBuffer);
    byte[] buffByte = new byte[i];
    // 转换ByteBuffer为读模式 也就是游标=0 读写上限limit=内容长度=游标
    byteBuffer.flip();
    byteBuffer.get(buffByte);
    System.out.println(new String(buffByte));
    socketChannel.close();
  }

你可能感兴趣的:(3、java.nio、ServerSocketChannel SocketChannel 堵塞模式使用)