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

Netty实现TCP通信

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

Netty实现TCP通信

Netty实现TCP通信 1 基本步骤

2 具体代码 2.1 服务端代码
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() {
                    
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new NettyTcpServerHandler());
                    }
                    
                    @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);
                    }
                });
        try {
            //绑定端口
            ChannelFuture channelFuture = bootstrap.bind(8888).sync();
            //关闭通道监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    
    static class NettyTcpServerHandler extends ChannelInboundHandlerAdapter {

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

        
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello World,I am Server.", CharsetUtil.UTF_8));
        }


        
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            //super.exceptionCaught(ctx, cause);
            ctx.close();
        }
    }
}
2.2 客户端代码
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() {
                    @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 {

        
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello World,I am Client.", CharsetUtil.UTF_8));
        }

        
        @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 执行原理

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

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

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