Netty:ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter

本文深入探讨了Netty中的ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter,详细介绍了它们的作用和常用方法,如channelActive、channelRead、channelReadComplete、exceptionCaught、bind和connect等,帮助读者理解Netty的事件处理机制。

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

Netty:ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter

 

前面说到,服务端和客户端通讯,我们通常要绑定一个handler(Netty:Bootstrap的handler和childHandler)进行通道的监听,当收到数据时就会触发某个事件,从而进行进一步的处理。

目前我们用的比较多的就是ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter。

ChannelInboundHandlerAdapter,看名字中的 IN,就是进入的意思,一般就是事件(event),比如当有数据到来时,channel被激活时或者不可用时,下面介绍几个最常用的。

 

channelActive

通道激活时触发,当客户端connect成功后,服务端就会接收到这个事件,从而可以把客户端的Channel记录下来,供后面复用

 

channelRead

这个必须用啊,当收到对方发来的数据后,就会触发,参数msg就是发来的信息,可以是基础类型,也可以是序列化的复杂对象。

 

channelReadComplete

channelRead执行后触发

 

exceptionCaught

出错是会触发,做一些错误处理

 

ChannelOutboundHandlerAdapter,看到了out,表示出去的动作,监听自己的IO操作,比如connect,bind等,在重写这个Adapter的方法时,记得执行super.xxxx,否则动作无法执行。

 

bind

服务端执行bind时,会进入到这里,我们可以在bind前及bind后做一些操作

 

connect

客户端执行connect连接服务端时进入

 

其它的操作可以参加Netty的官方文档http://netty.io/4.1/api/index.html

Groovy被设计得非常轻量级,很容易迁入到任何Java应用系统。
你可以使用BSF将Groovy脚本嵌入任何Java代码中.但是Groovy提供了一个轻量级的紧密集成.下面是3种主要方法:

1.使用Shell调试脚本或表达式
在Groovy中你可以使用GroovyShell对Groovy脚本和表达式进行调试.GroovyShell允许你通过Binding对象传入或传出变量.

// 从Java代码中调用Groovy语句
Binding binding = new Binding();
binding.setVariable("foo", new Integer(2));
GroovyShell shell = new GroovyShell(binding);

Object value = shell.evaluate("println 'Hello World!'; x = 123; return foo * 10");
assert value.equals(new Integer(20));
assert binding.getVariable("x").equals(new Integer(123));

当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错。

 

好的,下面是一个简单的 Netty 客户端服务端示例代码,可以相互发送消息: 服务端代码: ```java public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收客户端的消息 ByteBuf buf = (ByteBuf) msg; String request = buf.toString(CharsetUtil.UTF_8); System.out.println("Client request: " + request); // 向客户端发送响应消息 String response = "Hello, Client!"; ByteBuf respBuf = Unpooled.copiedBuffer(response, CharsetUtil.UTF_8); ctx.writeAndFlush(respBuf); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 客户端代码: ```java public class NettyClientHandler extends ChannelOutboundHandlerAdapter { private ChannelHandlerContext ctx; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { // 向服务器发送消息 ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8); ctx.writeAndFlush(buf); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收服务端的响应 ByteBuf buf = (ByteBuf) msg; String response = buf.toString(CharsetUtil.UTF_8); System.out.println("Server response: " + response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 启动代码: ```java public class NettyDemo { public static void main(String[] args) throws InterruptedException { // 创建 EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { // 创建 ServerBootstrap ServerBootstrap serverBootstrap = new ServerBootstrap(); // 配置 ServerBootstrap serverBootstrap.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(8888)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }); // 启动服务端 ChannelFuture serverFuture = serverBootstrap.bind().sync(); // 创建 Bootstrap Bootstrap clientBootstrap = new Bootstrap(); // 配置 Bootstrap clientBootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress("localhost", 8888)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyClientHandler()); } }); // 启动客户端 ChannelFuture clientFuture = clientBootstrap.connect().sync(); // 客户端向服务器发送消息 NettyClientHandler clientHandler = (NettyClientHandler) clientFuture.channel().pipeline().last(); clientHandler.write("Hello, Server!"); // 关闭客户端服务端 clientFuture.channel().closeFuture().sync(); serverFuture.channel().closeFuture().sync(); } finally { // 释放资源 group.shutdownGracefully().sync(); } } } ``` 在上面的代码中,服务端使用 `ChannelInboundHandlerAdapter` 处理客户端的请求,客户端使用 `ChannelOutboundHandlerAdapter` 向服务端发送请求。在启动代码中,先启动服务端,再启动客户端,并使用 `ChannelFuture` 对象获取客户端的 `NettyClientHandler` 对象,通过该对象向服务端发送消息。需要注意的是,客户端服务端都需要使用同一个 `EventLoopGroup`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值