加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Java IO学习笔记八:多路复用到Netty

发布时间:2023-04-18 14:17:42 所属栏目:教程 来源:
导读:多路复用多线程方式还是有点麻烦,Netty帮我们做了封装,大大简化了编码的复杂度,接下来熟悉一下netty的基本使用。

Netty+最朴素的阻塞的方式来实现一版客户端和服务端通信的代码,然后再重构成Netty官方推荐的写
多路复用多线程方式还是有点麻烦,Netty帮我们做了封装,大大简化了编码的复杂度,接下来熟悉一下netty的基本使用。

Netty+最朴素的阻塞的方式来实现一版客户端和服务端通信的代码,然后再重构成Netty官方推荐的写法。

第一步,引入netty依赖包。

<dependency>
   <groupId>io.netty</groupId>
   <artifactId>netty-all</artifactId>
   <version>4.1.65.Final</version>
</dependency>
准备发送端

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
 * @author <a href="mailto:">Grey</a>
 * @since
 */
public class NettyClientSync {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup thread = new NioEventLoopGroup(1);
        NioSocketChannel client = new NioSocketChannel();
        thread.register(client);
        ChannelPipeline p = client.pipeline();
        p.addLast(new MyInHandler());
        ChannelFuture connect = client.connect(new InetSocketAddress("192.168.205.138", 9090));
        ChannelFuture sync = connect.sync();
        ByteBuf buf = Unpooled.copiedBuffer("hello server".getBytes());
        ChannelFuture send = client.writeAndFlush(buf);
        send.sync();
        sync.channel().closeFuture().sync();
        System.out.println("client over....");
    }
    static class MyInHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRegistered(ChannelHandlerContext ctx) {
            System.out.println("client  register...");
        }
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            System.out.println("client active...");
        }
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf buf = (ByteBuf) msg;
            CharSequence str = buf.getCharSequence(0, buf.readableBytes(), UTF_8);
            System.out.println(str);
            ctx.writeAndFlush(buf);
        }
    }
}

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章