Netty 学习二

本文展示了如何使用 Netty 框架创建一个简单的服务端和客户端。服务端通过 ChannelInboundHandlerAdapter 处理接收到的客户端消息并回显,而客户端则发送一条消息并等待响应。服务端启动后监听指定端口,客户端连接到该端口进行通信。

一、简单的服务端与客户端

  1. 服务端
package com.zhu.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author gglove
 * @date 2022/6/13 21:07
 * @description:服务端处理器
 * @since 1.8
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        System.out.println("Server received client msg: " + in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

package com.zhu.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;

/**
 * @author gglove
 * @date 2022/6/14 20:24
 * @description: 服务端引导类
 * @since 1.8
 */
public class EchoServer {
    private int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        int port = 8099;
        new EchoServer(port).start();
    }

    public void start() throws Exception{
        final EchoServerHandler serverHandler = new EchoServerHandler();
        EventLoopGroup group = new NioEventLoopGroup(); //线程池
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class) //选择管道
                    .localAddress(new InetSocketAddress(port)) //绑定端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { //添加处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(serverHandler);
                        }
                    });
            ChannelFuture f = b.bind().sync();
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }

    }
}
  1. 客户端
package com.zhu.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author gglove
 * @date 2022/6/14 20:34
 * @description:客户端处理器
 * @since 1.8
 */
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("I am client!", CharsetUtil.UTF_8));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
        System.out.println("Client received :"  + in.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
package com.zhu.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;

/**
 * @author gglove
 * @date 2022/6/14 20:39
 * @description:客户端引导
 * @since 1.8
 */
public class EchoClient {
    private String host;

    private int port;

    public EchoClient(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).remoteAddress(new InetSocketAddress(host, port)).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new EchoClientHandler());
                }
            });
            ChannelFuture sync = b.connect().sync();
            sync.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        Integer port = 8099;
        new EchoClient(host, port).start();
    }
}

二、执行效果

服务端
在这里插入图片描述
客户端
在这里插入图片描述

### Netty 学习教程与入门指南 #### 什么是NettyNetty是一个基于NIO的客户、服务器端编程框架,提供了异步的、事件驱动的网络应用程序框架和工具,可以快速开发高可用的客户端和服务器[^3]。 #### Netty的核心组件 以下是Netty中的核心组件及其作用: - **EventLoop**: 负责处理I/O操作以及执行注册到其上的任务。 - **Channel**: 表示一个连接,用于读写数据。 - **Future**: 提供了一种机制来获取异步操作的结果。 - **Pipeline & Handler**: 处理链模式实现请求响应流程控制。`Pipeline`是一系列`Handler`组成的链条,负责拦截并处理消息流。 - **ByteBuf**: 更加高效灵活的字节容器替代传统的`ByteBuffer`[^1]。 #### Netty的主要优势 1. **API简单易用**:相比原始的Java NIO API,Netty封装了许多复杂细节,降低了开发难度。 2. **强大的功能支持**:内置多种编解码器和支持主流协议的功能模块。 3. **高度可定制化**:开发者可通过自定义`ChannelHandler`扩展通信逻辑。 4. **卓越性能表现**:经过大量测试表明,在相同条件下,Netty比其他NIO框架具有更高的吞吐量和更低延迟。 5. **稳定性强**:修复了已知的所有JDK NIO缺陷,并广泛应用于多个领域如Hadoop RPC框架Avro等实际生产环境中[^4]。 #### 初学者的第一个Netty Demo ("Hello World") 为了帮助理解如何使用Netty创建基本的应用程序,这里给出一段简单的Echo Server例子: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; 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 EchoServer { private final int port; public EchoServer(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() { // (4) @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(port).sync(); // (5) // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; if (args.length > 0) { port = Integer.parseInt(args[0]); } new EchoServer(port).start(); } } ``` 上述代码展示了如何设置一个基础的服务端启动过程,其中包含了两个线程组分别用来接受新的连接(`boss`) 和处理已建立好的连接 (`worker`) ,并通过管道添加处理器完成具体业务逻辑[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值