0
点赞
收藏
分享

微信扫一扫

NIO之同步阻塞

我是小瘦子哟 2022-03-30 阅读 44
java

NIO之同步阻塞


文章目录


前言

为了深入理解java中NIO的同步非阻塞功能,本文先从同步阻塞思想开始,了解NIO的基本原理。


一、POM包引入

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

二、同步非阻塞

1.服务端接受消息

1.1服务端代码

/**
     * 1. 服务端等待客户端建立连接
     * 2. 服务端接受客户端的数据并打印
     */
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        log.info("Connecting...");
        SocketChannel channel = serverSocketChannel.accept();
        log.info("Connected, channel={}", channel);
        while(true) {
            log.info("Before read, channel={}", channel);
            channel.read(buffer);
            buffer.flip();
            show(buffer);
            buffer.clear();
            log.info("After read, channel={}", channel);
        }
    }

1.2客户端代码

/**
     * 1. 客户端主动和服务端建立连接
     * 2. 客户端发送数据给服务端
     */
    public static void main(String[] args) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress("localhost", 8080));
        channel.write(Charset.defaultCharset().encode("Hello world\n"));
        channel.write(Charset.defaultCharset().encode("My name is lei\n"));
        channel.close();
    }

2.服务端推送消息

2.1服务端代码

代码如下(示例):

/**
     * 1. 服务端等待客户端建立连接
     * 2. 服务端推送数据给客户端
     */
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        log.info("Connecting...");
        SocketChannel channel = serverSocketChannel.accept();
        log.info("Connected, channel={}", channel);
        channel.write(Charset.defaultCharset().encode("Hi"));
        channel.close();
    }

2.1客户端代码

代码如下(示例):

/**
     * 1. 客户端主动和服务端建立连接
     * 2. 客户端接受服务端的数据并打印
     */
    public static void main(String[] args) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress("localhost", 8080));
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while(true) {
            channel.read(buffer);
            buffer.flip();
            show(buffer);
            buffer.clear();
        }
    }

总结

以上从服务端接受消息和服务端推送消息两个例子实现了同步阻塞模式的消息通信,下一章节将实现同步非阻塞通信模式。

举报

相关推荐

NIO阻塞与非阻塞式

NIO 非阻塞IO

0 条评论