博客
关于我
Netty入门 - (秒懂)- 图解Netty系列
阅读量:299 次
发布时间:2019-03-03

本文共 3884 字,大约阅读时间需要 12 分钟。

Netty 入门

前言

在现代网络应用开发中,协议的选择至关重要。通用协议如HTTP和TCP虽然功能强大,但在处理高频率的实时数据或大规模数据传输时往往显得力不从心。这种情况下,我们需要专门设计或优化协议以满足特定需求。Netty作为一个高性能、易于使用的NIO框架,正是为此而生,它能够帮助开发者快速构建高效的网络协议服务器和客户端。

本文将从基础的Netty入门开始,逐步介绍Netty的核心概念和实际应用。

项目搭建

首先,我们需要创建一个Netty项目。以下是项目的基本设置:

  • 项目名称:NettyDemo
  • 开发工具:建议使用JDK 1.8及以上版本
  • 依赖管理:通过Maven引入Netty相关依赖
  • io.netty
    netty-all
    4.1.6.Final

    通过上述配置,我们已经完成了Netty项目的基本设置,接下来可以开始编写实际的网络应用程序了。

    Discard 处理器

    在学习Netty之前,我们需要理解其核心概念之一——处理器(Handler)。处理器用于定义如何响应或处理网络事件,比如数据接收、异常处理等。

    Discard服务器的实现

    Discard服务器的设计目标是丢弃所有接收到的数据。这种处理方式的核心在于实现一个“无所谓”的协议,任何发送给服务器的数据都会被直接忽略。

    package netty_beginner;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;public class DiscardServerHandler extends ChannelInboundHandlerAdapter {    @Override    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {        // 解决方案:直接释放消息        ((ByteBuf) msg).release();        ByteBuf in = (ByteBuf) msg;        try {            while (in.isReadable()) {                System.out.print((char) in.readByte());                System.out.flush();            }        } finally {            ReferenceCountUtil.release(msg);        }    }    @Override    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {        cause.printStackTrace();        ctx.close();    }}
    • channelRead方法:当服务器接收到数据时,会调用此方法。我们在这里释放了接收到的消息,并直接忽略其内容。
    • exceptionCaught方法:当发生异常时,捕获异常并打印,最后关闭连接。

    通过上述处理器,我们已经完成了Discard服务器的核心逻辑实现。

    服务器实现

    接下来,我们需要创建一个Discard服务器的主类,负责初始化服务器配置并启动服务。

    package netty_beginner;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 DiscardServer {    private int port;    public DiscardServer(int port) {        this.port = port;    }    public void run() throws InterruptedException {        EventLoopGroup bossGroup = new NioEventLoopGroup();        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap bootstrap = new ServerBootstrap();            bootstrap.group(bossGroup, workerGroup)                    .channel(NioServerSocketChannel.class)                    .childHandler(new ChannelInitializer
    () { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new DiscardServerHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { int port = (args.length > 0) ? Integer.parseInt(args[0]) : 8080; new DiscardServer(port).run(); }}
    • bossGroup和workerGroup:这两个事件循环线程组负责处理网络连接和I/O操作。bossGroup负责接收新连接,workerGroup负责处理连接的读写。
    • ServerBootstrap:这是一个帮助类,用于配置和启动服务器。我们指定了使用NioServerSocketChannel作为服务器通道。
    • ChannelInitializer:这是一个用于配置新连接的处理程序,确保每个新连接都注册了DiscardServerHandler。

    通过上述主类,我们可以轻松启动一个Discard服务器,接收客户端的数据并直接丢弃。

    测试与验证

    为了验证服务器的工作是否正常,我们可以使用telnet客户端进行测试。

  • 打开终端,输入telnet localhost 8080,建立一个连接。
  • 输入任意文本内容(如hello),观察是否会在控制台输出相应的字符。
  • 如果一切正常,你应该会看到控制台输出你发送的每个字符,这表明服务器正在正确接收数据并进行丢弃。

    总结

    通过本文的步骤,我们已经掌握了Netty入门的基本知识,包括项目搭建、处理器实现以及服务器配置。Netty的强大功能使得开发高性能网络协议应用变得异常简单,接下来可以通过实际项目进一步探索Netty的更多功能。

    转载地址:http://effm.baihongyu.com/

    你可能感兴趣的文章
    Nginx代理静态资源(gis瓦片图片)实现非固定ip的url适配网络环境映射ip下的资源请求解决方案
    查看>>
    Nginx反向代理与正向代理配置
    查看>>
    Nginx反向代理是什么意思?如何配置Nginx反向代理?
    查看>>
    nginx反向代理解决跨域问题,使本地调试更方便
    查看>>
    nginx启动脚本
    查看>>
    Nginx在Windows下载安装启动与配置前后端请求代理
    查看>>
    Nginx多域名,多证书,多服务配置,实用版
    查看>>
    nginx开机启动脚本
    查看>>
    nginx异常:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf
    查看>>
    nginx总结及使用Docker创建nginx教程
    查看>>
    nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
    查看>>
    nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in usrlocalnginxconfnginx.conf128
    查看>>
    nginx日志分割并定期删除
    查看>>
    Nginx日志分析系统---ElasticStack(ELK)工作笔记001
    查看>>
    Nginx映射本地json文件,配置解决浏览器跨域问题,提供前端get请求模拟数据
    查看>>
    nginx最最最详细教程来了
    查看>>
    Nginx服务器---正向代理
    查看>>
    Nginx服务器上安装SSL证书
    查看>>
    Nginx服务器的安装
    查看>>
    Nginx模块 ngx_http_limit_conn_module 限制连接数
    查看>>