首页 > 其他分享 >netty入门demo

netty入门demo

时间:2023-06-04 20:46:18浏览次数:46  
标签:netty 入门 demo ctx io new import channel

参考博客:(14条消息) 【Netty整理01-快速入门】Netty简单使用Demo(已验证)_the_fool_的博客-CSDN博客

ServerHandler.java

package com.hmb;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server read....");
        ByteBuf buf = (ByteBuf) msg;
        byte[] date = new byte[buf.readableBytes()];
        buf.readBytes(date);
        System.out.println("client msg: " + new String(date));
        buf.release();

        System.out.println("send msg to client...");
        String response = "hello client";
        ByteBuf buf1 = ctx.alloc().buffer();
        buf1.writeBytes(response.getBytes());
        ctx.write(buf1);
        ctx.flush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}

  

NettyServer.java

package com.hmb;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    private int port = 9999;

    public void start() {
        EventLoopGroup worker = new NioEventLoopGroup();
        EventLoopGroup boss = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ServerHandler());
                    }
                });

        try {
            ChannelFuture cf = serverBootstrap.bind(port).sync();
            cf.channel().closeFuture() .sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyServer server = new NettyServer();
        server.start();
    }
}

  

ClientHandler.java

package com.hmb;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("read msg from server...");
        ByteBuf buf = (ByteBuf) msg;
        byte[] date = new byte[buf.readableBytes()];
        buf.readBytes(date);
        System.out.println("server msg: " + new String(date));
        buf.release();

        Thread.sleep(10000);
        System.out.println("send msg to server...");
        String response = "hello server";
        ByteBuf buf1 = ctx.alloc().buffer();
        buf1.writeBytes(response.getBytes());
        ctx.write(buf1);
        ctx.flush();
    }

    /**
     * channel生命周期回调函数,channel准备好后回调此函数,不能少,否则bs交互无法发起
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("firstly send msg to server...");
        String msg = "hello server!";
        ByteBuf encode = ctx.alloc().buffer(4 * msg.length());
        encode.writeBytes(msg.getBytes());
        ctx.write(encode);
        ctx.flush();
    }
}

  

NettyClient.java

package com.hmb;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
    public void connect(String host, int port) {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ClientHandler());
                    }
                });

        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();
        nettyClient.connect("127.0.0.1", 9999);
    }
}

  

先运行NettyServer.java的main方法,再运行NettyClient.java的main方法,此时就可以看到bs的交互信息

 

 

标签:netty,入门,demo,ctx,io,new,import,channel
From: https://www.cnblogs.com/hemeiwolong/p/17456267.html

相关文章

  • Python爬虫入门六之Cookie的使用
     大家好哈,上一节我们研究了一下爬虫的异常处理问题,那么接下来我们一起来看一下Cookie的使用。为什么要使用Cookie呢?Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)比如说有些网站需要登录后才能访问某个页面,在登录之前,你想抓取某个......
  • 常用插件的使用—grunt入门指南(下)
    less/sass/stylus预编译在前端工程中使用css预编译器(less/sass/stylus)用于弥补css的语言缺陷,基本上是标配了,其中less和sass用的最多,但明河最喜欢使用的是stylus,grunt官方有对应的编译插件。这里以grunt-contrib-stylus为例。stylus:{options:{//......
  • 任务配置详解—grunt入门指南
    任务配置指的是grunt.initConfig({})中的任务配置,上一篇文章我们配置了uglify(这里指任务名,而不是插件名)任务,用于压缩js文件,接单演示了任务配置的功能。这一篇教程将深入讲解任务配置的细节。多任务目标构建中有二个关键字:任务(task)和目标(target),一个任务可以包含多个任务目标。grunt.......
  • WPF入门教程系列二十七 ——DataGrid使用示例MVVM模式(4)
    WPF入门教程系列目录WPF入门教程系列二——Application介绍WPF入门教程系列三——Application介绍(续)WPF入门教程系列四——Dispatcher介绍WPF入门教程系列五——Window介绍WPF入门教程系列十一——依赖属性(一)WPF入门教程系列十五——WPF中的数据绑定(一)   ......
  • .net 温故知新【11】:Asp.Net Core WebAPI 入门使用及介绍
    在Asp.NetCore上面由于现在前后端分离已经是趋势,所以asp.netcoreMVC用的没有那么多,主要以WebApi作为学习目标。一、创建一个WebApi项目我使用的是VS2022,.Net7版本。在创建界面有几项配置:配置Https启用Docker使用控制器启用OpenAPI支持不使用顶级语句其中配置Ht......
  • 异步爬虫demo2
    importreimportaiohttpimportasyncioclassAsyn:def__init__(self):self.__headers={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/112.0.0.0Safari/537......
  • Kubescape入门
    Kubescape是一个K8sopen-source工具,提供multi-cloudK8s单层玻璃,包括风险分析、安全合规性、RBAC可视化工具和图像漏洞扫描。Kubescape在CI/CD管道的早期阶段扫描K8s集群、YAML文件和HELM图表,根据多个框架(例如NSA-CISA、MITREATT&CK®)、软件漏洞和RBAC(role-based-access-control)......
  • CXF入门教程(2) -- 第一个客户端
    文中对应的代码已经上传,与教程(1)中的service相对应。为调试方便,将service和client都放在了同一个工程中,不过是在不同的包中;本文对应的两个基本客户端在com.neareast.test.cxf.client.consumer包中,服务端ServiceTest类在com.neareast.test.cxf.server.service包中。代码地址如下:最常......
  • JBPM5入门资料
    [color=darkblue][b]jBPM5.4-01:jbpm-5.4.0安装[/b][/color][url]http://xujava.iteye.com/blog/1839918[/url][color=red][b]jbpm5创建SimpleDemo步骤[/b][/color]:[url]http://wenku.baidu.com/view/dccf328e84868762caaed5b8.html[/url][color=red][b]J......
  • Service的入门教程
    [b][color=red]Webservice是什么[/color][/b][url]http://www.ruanyifeng.com/blog/2009/08/what_is_web_service.html[/url]生成客户端Java代码的两个命令:会保留service的package结构[color=red]wsdl2java-dd:\src-clienthttp://localhost:8080/Ser......