Java 基于Netty客户端 01【客户端发送消息、服务器读取】

server

package cn.itcast.netty.c2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LoggingHandler;

public class HelloServer {
    public static void main(String[] args) {
        // 1. 启动器,负责组装 netty 组件,启动服务器
        new ServerBootstrap()
            // 2. BossEventLoop, WorkerEventLoop(selector,thread), group 组
            .group(new NioEventLoopGroup())
            // 3. 选择 服务器的 ServerSocketChannel 实现
            .channel(NioServerSocketChannel.class) // OIO BIO
            // 4. boss 负责处理连接 worker(child) 负责处理读写,决定了 worker(child) 能执行哪些操作(handler)
            .childHandler(
                    // 5. channel 代表和客户端进行数据读写的通道 Initializer 初始化,负责添加别的 handler
                new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    // 6. 添加具体 handler
                    ch.pipeline().addLast(new LoggingHandler());
                    ch.pipeline().addLast(new StringDecoder()); // 将 ByteBuf 转换为字符串
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 自定义 handler
                        @Override // 读事件
                        public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception {
                            System.out.println(msg); // 打印上一步转换好的字符串
                        }
                    });
                }
            })
            // 7. 绑定监听端口
            .bind(8080);
    }
}
  1. 创建ServerBootstrap:创建了一个ServerBootstrap实例,用于组装Netty组件并启动服务器。

  2. 设置EventLoopGroup:通过.group(new NioEventLoopGroup())设置了一个NioEventLoopGroup,用于管理服务器端的事件循环。这个事件循环组包含了两种类型的事件循环:BossEventLoop和WorkerEventLoop。BossEventLoop负责处理连接请求,而WorkerEventLoop负责处理连接的读写操作。

  3. 设置服务器的Channel类型:通过.channel(NioServerSocketChannel.class)选择了NIO作为服务器的通信模式,使用NioServerSocketChannel作为服务器的Channel实现。

  4. 设置ChildHandler:通过.childHandler()方法设置了一个ChannelInitializer,用于配置新连接的Channel。在这个初始化器中,添加了多个ChannelHandler来处理数据的读写和处理。

  5. 初始化ChannelPipeline:在initChannel方法中,初始化了新连接的ChannelPipeline,用于管理数据处理的流水线。在这里,添加了三个ChannelHandler到Pipeline中:

    • LoggingHandler:用于打印日志。
    • StringDecoder:用于将ByteBuf转换为字符串。
    • ChannelInboundHandlerAdapter:自定义的Handler,继承自ChannelInboundHandlerAdapter,重写了channelRead方法,在这个方法中处理读事件,将接收到的消息打印到控制台。
  6. 绑定监听端口:通过.bind(8080)方法绑定了服务器的监听端口为8080,开始监听客户端连接。

这段代码演示了使用Netty构建一个简单的服务器端程序,它能够接受客户端的连接请求,并在收到数据时进行处理和打印。

client

package cn.itcast.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        // 1. 启动类
        new Bootstrap()
            // 2. 添加 EventLoop
            .group(new NioEventLoopGroup())
            // 3. 选择客户端 channel 实现
            .channel(NioSocketChannel.class)
            // 4. 添加处理器
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override // 在连接建立后被调用
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new StringEncoder());
                }
            })
            // 5. 连接到服务器
            .connect(new InetSocketAddress("localhost", 8080))
            .sync()
            .channel()
            // 6. 向服务器发送数据
            .writeAndFlush("hello, world");
    }
}
  1. 创建Bootstrap:创建了一个Bootstrap实例,用于启动客户端。

  2. 设置EventLoopGroup:通过.group(new NioEventLoopGroup())设置了一个NioEventLoopGroup,用于处理客户端的事件循环。

  3. 设置客户端的Channel类型:通过.channel(NioSocketChannel.class)选择了NIO作为客户端的通信模式,使用NioSocketChannel作为客户端的Channel实现。

  4. 添加Handler:通过.handler()方法设置了一个ChannelInitializer,用于配置新连接的Channel。在这个初始化器中,添加了一个StringEncoder,用于将字符串编码为ByteBuf发送给服务器。

  5. 连接到服务器:通过.connect(new InetSocketAddress("localhost", 8080)).sync()方法连接到指定的服务器地址和端口,并同步等待连接完成。获取到连接成功后的Channel对象。

  6. 向服务器发送数据:通过.writeAndFlush("hello, world")向服务器发送一条消息。

这段代码演示了使用Netty构建一个简单的客户端程序,它能够连接到指定的服务器并发送消息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值