栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

NIO之同步阻塞

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

NIO之同步阻塞

NIO之同步阻塞模式

文章目录

NIO之同步阻塞模式前言一、POM包引入二、服务端接受消息

2.1 服务端代码2.2 客户端代码 三、服务端推送消息

3.1 服务端代码3.2 客户端代码 总结


前言

为了深入理解java中NIO的同步非阻塞功能,本文从同步阻塞模式开始,开发了服务端接受消息和推送消息的Demo,以便后续学习同步非阻塞模式打下基础。


一、POM包引入
        
            org.projectlombok
            lombok
            1.18.10
        
        
            com.google.code.gson
            gson
            2.8.5
        
        
            ch.qos.logback
            logback-classic
            1.2.3
        
二、服务端接受消息 2.1 服务端代码

代码如下(示例):

    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);
        }
    }
2.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 worldn"));
        channel.write(Charset.defaultCharset().encode("My name is lein"));
        channel.close();
    }
三、服务端推送消息 3.1 服务端代码

代码如下(示例):

    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();
    }
3.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();
        }
    }

总结

以上从服务端接受消息和服务端推送消息的两个例子可以看出服务端同一时间只能和一个客户端建立连接并实现通信,下一章节将实现同步非阻塞模式的通信方式以作对比。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781375.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号