Netty实现TCP通信

简介: Netty实现TCP通信

Netty实现TCP通信

1 基本步骤

2 具体代码

2.1 服务端代码
/**
 * @desc: Server端
 * @author: YanMingXin
 * @create: 2021/9/27-15:30
 **/
public class NettyTcpServer {
    public static void main(String[] args) {
        //boosGroup处理连接请求
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        //workGroup处理真正的业务逻辑
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //服务端启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();
        //配置启动对象参数
        //设置两个线程组
        bootstrap.group(boosGroup, workGroup)
                //channel类型为NioServerSocketChannel
                .channel(NioServerSocketChannel.class)
                //线程队列的连接个数
                .option(ChannelOption.SO_BACKLOG, 128)
                //线程队列的状态
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //配置子处理器(匿名类)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    /**
                     * 初始化阶段
                     * @param socketChannel
                     * @throws Exception
                     */
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new NettyTcpServerHandler());
                    }
                    /**
                     * 发生异常处理
                     * @param ctx
                     * @param cause
                     * @throws Exception
                     */
                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        super.exceptionCaught(ctx, cause);
                    }
                    /**
                     * 添加新的处理器
                     * @param ctx
                     * @throws Exception
                     */
                    @Override
                    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                        super.handlerAdded(ctx);
                    }
                });
        try {
            //绑定端口
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();
            //关闭通道监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
    /**
     * 自定义Handler
     */
    static class NettyTcpServerHandler extends ChannelInboundHandlerAdapter {
        /**
         * 管道读取数据
         *
         * @param ctx
         * @param msg
         * @throws Exception
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            System.out.println(byteBuf.toString(StandardCharsets.UTF_8));
            System.out.println(ctx.channel().remoteAddress());
        }
        /**
         * 读取数据完毕
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello World,I am Server.", CharsetUtil.UTF_8));
        }
        /**
         * 异常处理
         *
         * @param ctx
         * @param cause
         * @throws Exception
         */
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            //super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    }
}
2.2 客户端代码
/**
 * @desc: Client端
 * @author: YanMingXin
 * @create: 2021/9/27-15:30
 **/
public class NettyTcpClient {
    public static void main(String[] args) {
        //处理连接请求的NioEventLoopGroup
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        //服务对象
        Bootstrap bootstrap = new Bootstrap();
        //配置服务参数
        bootstrap.group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyTcpClientHandler());
                    }
                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        super.exceptionCaught(ctx, cause);
                    }
                    @Override
                    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                        super.handlerAdded(ctx);
                    }
                });
        //连接服务器端
        ChannelFuture connect = bootstrap.connect("127.0.0.1", 8888);
        try {
            //关闭连接
            connect.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            nioEventLoopGroup.shutdownGracefully();
        }
    }
    /**
     * 处理器
     */
    static class NettyTcpClientHandler extends ChannelInboundHandlerAdapter {
        /**
         * 管道就绪则处理该方法
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello World,I am Client.", CharsetUtil.UTF_8));
        }
        /**
         * 通道读取事件时会触发
         *
         * @param ctx
         * @param msg
         * @throws Exception
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            System.out.println(byteBuf.toString(CharsetUtil.UTF_8));
            System.out.println(ctx.channel().remoteAddress());
        }
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
}

3 执行原理

相关文章
|
3月前
|
网络协议
【Netty 网络通信】Socket 通信原理
【1月更文挑战第9天】【Netty 网络通信】Socket 通信原理
|
3月前
|
Java Maven
【Netty 网络通信】启动通信服务端
【1月更文挑战第9天】【Netty 网络通信】启动通信服务端
|
16天前
|
网络协议 Java 物联网
Spring Boot与Netty打造TCP服务端(解决粘包问题)
Spring Boot与Netty打造TCP服务端(解决粘包问题)
26 1
|
16天前
|
移动开发 网络协议 Java
通信密码学:探秘Netty中解码器的神奇力量
通信密码学:探秘Netty中解码器的神奇力量
21 0
|
3月前
|
负载均衡 Java 调度
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(Dispatcher和EventListener)(下)
经过阅读《【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)》,相信您已经对网络通信框架的网络通信层的实现原理和协议模型有了一定的认识和理解。
41 0
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(Dispatcher和EventListener)(下)
|
3月前
|
Dubbo Java 应用服务中间件
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
今天,我要向大家实现一个基于Netty实现的高性能远程通信框架!这个框架利用了 Netty 的强大功能,提供了快速、可靠的远程通信能力。 无论是构建大规模微服务架构还是实现分布式计算,这个分布式通信框架都是一个不可或缺的利器。
64 2
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
|
3月前
|
前端开发 Java Maven
【Netty 网络通信】启动客户端连接服务端实现通信
【1月更文挑战第9天】【Netty 网络通信】启动客户端连接服务端实现通信
|
3月前
|
编解码
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战_自定义长度分包编解码码器
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战_自定义长度分包编解码码器
46 0
|
3月前
|
网络协议
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战
Netty Review - 优化Netty通信:如何应对粘包和拆包挑战
50 0
|
7月前
|
监控 Java Linux
由浅入深Netty基础知识NIO网络编程1
由浅入深Netty基础知识NIO网络编程
40 0