Netty实现简单服务端和客户端通信

Netty实现简单服务端和客户端通信

服务端代码

/**
 * @version 1.0.0
 * @Description TODO
 * @createTime 2022年04月03日 17:11:00
 */
public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new StringDecoder());
                        channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
                                System.out.println(s);
                            }
                        });
                    }
                })
        .bind(8000);
    }
}

客户端代码 :

/**
 * @version 1.0.0
 * @Description TODO
 * @createTime 2022年04月03日 17:26:00
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());
                    }
                });

        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();

        while (true) {
            channel.writeAndFlush(new Date() + " : hello world");
            Thread.sleep(20000);
        }
    }
}

依赖版本 :

<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.7.Final</version>
        </dependency>

现在netty最新版本到4.1.75,不过4.1.10以下版本支持JDK1.8, Netty的4.1.10以上的版本支持大于JDK9的版本,所以这块没有使用最新的版本.
另外一些涉及到IO的中间件或其它微服务组件也会用到Netty,下面看一下我的Demo依赖中 redis 中使用到了最新的Netty版本
在这里插入图片描述
从依赖中我们也可以看到底层通信确实有使用到netty,那么项目中有用到这些组件的话,其实不用再一次引入netty的依赖了

关于版本这个在启动后日志输出上我们也可以看出有提示jdk版本
在这里插入图片描述

关于netty的简单使用,及一些小问题就到这里了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值