Netty|02 easy example

入门案例

1、博主使用的IDE是idea,很强大的开发工具
2、为了精简篇幅,博主把代码中需要导入包那一块去除了,大家在操作的时候需要手动导包
3、入门案例的每一行代码都有对应的注释,便于大家理解

1、新建maven项目并且导入Netty的对应坐标

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

2、新建NettyServer

public class NettyServer {    public static void main(String[] args) throws InterruptedException {//        创建线程池 接受连接        NioEventLoopGroup bossGroup = new NioEventLoopGroup();//        创建线程池,处理io        NioEventLoopGroup workGroup = new NioEventLoopGroup();//        创建服务器端启动助手        ServerBootstrap serverBootstrap = new ServerBootstrap();//        配置启动助手        serverBootstrap.group(bossGroup, workGroup)//设置两个线程池                .channel(NioServerSocketChannel.class)//使用作为服务器端的通道实现                .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列中等待连接的个数                .childOption(ChannelOption.SO_KEEPALIVE, true)//保持活动连接状态                .childHandler(new ChannelInitializer<SocketChannel>() { //创建通道初始化的对象                    @Override                    protected void initChannel(SocketChannel ch) throws Exception {                        ch.pipeline().addLast(new NettyServerHandler());                    }                });        System.out.println("----------------server is ready--------------------");        ChannelFuture cf = serverBootstrap.bind(9999).sync();//绑定端口,异步        System.out.println("----------------server is starting--------------------");//        关闭通道、关闭通道组        cf.channel().closeFuture().sync();        bossGroup.shutdownGracefully();        workGroup.shutdownGracefully();
    }}

3、新建服务器业务处理块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:"+ctx);        ByteBuf buf = (ByteBuf)msg;        System.out.println("客户端发来消息:"+buf.toString(CharsetUtil.UTF_8));
    }
    /**     *数据读取完毕     * @param ctx     * @throws Exception     */    @Override    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {        ctx.writeAndFlush(Unpooled.copiedBuffer("就是没钱啦!",CharsetUtil.UTF_8));    }
    /**     * 异常发生     * @param ctx     * @param cause     * @throws Exception     */    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        ctx.close();    }}

4、新建客户端NettyClient

public class NettyClient {    public static void main(String[] args) throws InterruptedException {
//        创建一个线程组        NioEventLoopGroup group = new NioEventLoopGroup();        //2. 创建客户端的启动助手,完成相关配置        Bootstrap bootstrap = new Bootstrap();        bootstrap.group(group)//3. 设置线程组                .channel(NioSocketChannel.class)//4. 设置客户端通道的实现类                .handler(new ChannelInitializer<SocketChannel>() {//5. 创建一个通道初始化对象                    @Override                    protected void initChannel(SocketChannel ch) throws Exception {                        ch.pipeline().addLast(new NettyClientHandler());//6.往Pipeline链中添加自定义的handler                    }                });        System.out.println("......Client is  ready......");
        //7.启动客户端去连接服务器端  connect方法是异步的   sync方法是同步阻塞的        ChannelFuture cf = bootstrap.connect("127.0.0.1", 9999).sync();
//        关闭连接        cf.channel().closeFuture().sync();
    }}

5、新建客户端业务处理NettyClientHandler

public class NettyClientHandler extends ChannelInboundHandlerAdapter {    /**     * 通道就绪事件     * @param ctx     * @throws Exception     */    @Override    public void channelActive(ChannelHandlerContext ctx) throws Exception {        System.out.println("client:"+ctx);        ctx.writeAndFlush(Unpooled.copiedBuffer("老板还钱吧!", CharsetUtil.UTF_8));    }
    /**     * 读取数据     * @param ctx     * @param msg     * @throws Exception     */    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        ByteBuf buf = (ByteBuf)msg;        System.out.println("服务器发来消息:"+buf.toString(CharsetUtil.UTF_8));    }}

6、运行结果:

服务器端
----------------server is ready--------------------
----------------server is starting--------------------
server:ChannelHandlerContext(NettyServerHandler#0, [id: 0xa80ee519, L:/127.0.0.1:9999 - R:/127.0.0.1:60798])
客户端发来消息:老板还钱吧!
客户端:
......Client is ready......
client:ChannelHandlerContext(NettyClientHandler#0, [id: 0xe77a3b4a, L:/127.0.0.1:60798 - R:/127.0.0.1:9999])
服务器发来消息:就是没钱啦!

小哥哥小姐姐,

看完了可不可以点个在看~(づ ̄3 ̄)づ╭❤~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值