Java nio Client端简单示例

java nio是一种基于Channel、Selector、Buffer的技术,它是一种非阻塞的IO实现方式

以下Client端示例

public class ClientNio {

    public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();   //打开一个socket 通道
//        socketChannel.configureBlocking(false);

//      Selector selector = Selector.open();

//        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress("127.0.0.1",8099)); //连接到server端8099端口

        ByteBuffer byteBuffer = ByteBuffer.allocate(4);   //开辟4个字节的内存
        byteBuffer.clear();
        int a = 222;

        try {
            byteBuffer.put((byte) (a >> 24));   //将4个字节从高位到低位分别放到byteBuffer中
            byteBuffer.put((byte) (a >> 16));
            byteBuffer.put((byte) (a >> 8));
            byteBuffer.put((byte) (a));
            byteBuffer.flip();  //切换写模式到读模式
            while (byteBuffer.hasRemaining()) {
                socketChannel.write(byteBuffer);  //写入通道中,服务端可接受这些信息
            }
//            socketChannel.shutdownInput();
        }finally {
            socketChannel.close();
        }
        Thread.sleep(5000);

        System.out.println("exit");
    }

}

猜你喜欢

转载自www.cnblogs.com/windliu/p/9588163.html