一个简单的Netty demo

本文介绍了Netty的基础知识和一个简单的入门示例,包括新建Maven项目,配置服务端和客户端,以及自定义编解码器。Netty是一个高性能的异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。文章还深入探讨了Netty的核心类、传输方式和编解码器原理,并提到了其对HTTP等协议的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Netty是什么,它可以做什么

    Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。

    简单来说,Netty是一个对java nio的封装,用于快速简单的开发高性能网络应用程序的工具。

    参考资料: netty官网: http://netty.io/

                        权威书籍:《Netty In Action》 (https://download.youkuaiyun.com/download/weixin_37068368/10377062)

                        官方样例:https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example

                        参考博客:https://blog.youkuaiyun.com/h348592532/article/details/52816148#

    样例代码github地址:https://github.com/WeedOutWorld/techDemo/tree/master

2. Netty 入门demo

      配置服务端与客户端,自定义协议。配置完成项目后,先启动服务端EchoServer.java,再启动客户端EchoClient.java

    2.1. 新建一个maven项目,并导入Netty依赖包

        工程结构:

        

        maven依赖:

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

    2.2. 服务端 

        Netty服务端主要有两部分构成:服务端配置启动类,业务逻辑处理类(异步回调接口)

        服务端配置启动类:

package org.ych.techDemo.netty.nettyServer;

import org.ych.techDemo.netty.encoder.MessageDecoder;
import org.ych.techDemo.netty.encoder.MessageEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * Echoes back any received data from a client.
 */
public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {
    	System.out.println("EchoServer.main start");
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // Configure the server.
        /*步骤
         * 创建一个ServerBootstrap b实例用来配置启动服务器
         * b.group指定NioEventLoopGroup来接收处理新连接
         * b.channel指定通道类型
         * b.option设置一些参数
         * b.handler设置日志记录
         * b.childHandler指定连接请求,后续调用的channelHandler
         * b.bind设置绑定的端口
         * b.sync阻塞直至启动服务
        */
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             //.option(ChannelOption.SO_BACKLOG, 100)
             //.handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc()));
                     }
                     p.addLast(new MessageDecoder());
           
### 回答1: 好的,以下是一个简单Netty Demo: 首先,需要在代码中导入Netty的相关库,例如Maven中的netty-all: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.51.Final</version> </dependency> ``` 然后,可以创建一个Echo服务器,该服务器将接受客户端的消息并将其返回给客户端。以下是示例代码: ```java public class EchoServer { private int port; public EchoServer(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); ChannelFuture f = b.bind().sync(); System.out.println("EchoServer started and listening on " + f.channel().localAddress()); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: " + EchoServer.class.getSimpleName() + " <port>"); return; } int port = Integer.parseInt(args[0]); new EchoServer(port).start(); } } ``` 最后,还需要一个EchoServerHandler类,该类将在服务器收到消息时处理它们并将它们返回给客户端。以下是示例代码: ```java public class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.write(msg); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 这是一个简单Netty Demo,它创建了一个Echo服务器,当客户端连接并发送消息时,服务器将把消息返回给客户端。 ### 回答2: Netty一个基于Java NIO的网络通信框架,具有高性能、高可靠和易于使用的特点。下面是一个简单Netty Demo示例,演示如何使用Netty创建一个简单的服务器和客户端进行通信。 首先,在项目中添加Netty的依赖,例如在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.42.Final</version> </dependency> ``` 然后,创建一个服务器类Server和一个客户端类Client。 Server类代码示例: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class Server { private int port; public Server(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); // 处理连接请求 EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理连接的IO操作 try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(new ServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); // 绑定端口 f.channel().closeFuture().sync(); // 监听关闭事件 } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8888; Server server = new Server(port); server.start(); } } ``` Client类代码示例: ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class Client { private String host; private int port; public Client(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(new ClientHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); // 连接服务器 f.channel().closeFuture().sync(); // 监听关闭事件 } finally { group.shutdownGracefully(); } } public static void main(String[] args) throws Exception { String host = "localhost"; int port = 8888; Client client = new Client(host, port); client.start(); } } ``` 以上是一个简单Netty Demo示例,演示了如何使用Netty创建一个简单的服务器和客户端进行通信。在示例中,服务器和客户端都使用了相同的处理器类ServerHandler和ClientHandler进行消息的编解码和处理。可以根据实际需求进行进一步的扩展和改造。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值