ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Netty简单Demo

2021-11-09 22:58:16  阅读:142  来源: 互联网

标签:Netty Exception Demo void ctx param public 简单 throws


netty server:

public class NettyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);//处理连接请求
        EventLoopGroup workerGroup=new NioEventLoopGroup();//默认线程数量为cpu核数的两倍,处理业务
        try {
            ServerBootstrap bootstrap=new ServerBootstrap();//创建服务器端的启动对象
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("netty server start");
            //启动服务器绑定端口,bind是异步操作,sync是等待
            ChannelFuture cf=bootstrap.bind(9000).sync();

            cf.channel().closeFuture().sync();
            System.out.println("******************server close");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
NettyServerHandler:
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取客户端的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server 读取数据线程"+Thread.currentThread().getName());

        ByteBuf byteBuf= (ByteBuf) msg;
        System.out.println("收到客户端发送的消息:"+byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 数据读取完毕处理方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf= Unpooled.copiedBuffer("Hello Client".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 处理异常一般是关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
NettyClient
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group=new NioEventLoopGroup();
        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(new NettyClientHandler());//
                        }
                    });
            System.out.println("netty client start");
            //启动客户端连接服务器
            ChannelFuture cf =bootstrap.connect("127.0.0.1",9000).sync();
            //关闭通道进行监听
            cf.channel().closeFuture().sync();
            System.out.println("********************client close");
        } finally {
            group.shutdownGracefully();
        }
    }
}
NettyClientHandler
public class NettyClientHandler  extends ChannelInboundHandlerAdapter {

    /**
     * 当客户端连接到服务端是触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf byteBuf= Unpooled.copiedBuffer("Hello Server".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 读取服务端发送的数据
     * @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());
    }

    /**
     * 处理异常一般是关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

标签:Netty,Exception,Demo,void,ctx,param,public,简单,throws
来源: https://blog.csdn.net/dingruibao/article/details/121238869

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有