Files
rikako-note/netty/netty.md
2023-01-16 18:36:59 +08:00

38 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Netty
## Netty适用场景
目前http协议被广泛用于web服务器和客户端之间的交流但是在一些场景下http协议不能够很好的拓展。
如在交换大文件、email信息或实时信息如多人游戏数据和经济信息等场景下通常不使用通用http协议而是需要为特定需求优化过使用特定场景的协议。
## Netty介绍
Netty Project提供了异步事件驱动的网络应用框架并为快速开发和维护高性能、高拓展的协议服务器和客户端提供工具。
Netty是开发协议服务器和客户端的NIO开发框架提供了开发快速和简单开发协议服务器和客户端的方式。其大大简化了网络开发例如tcp和udp套接字编程过程。
## Netty Demo
### Discard Demo
如果要通过netty实现一个丢弃接收数据的server可以参照如下实现。如下的handler实现用于处理由netty产生的IO事件
```java
package io.netty.example.discard;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandlerAdapter;
/**
* Handles a server-side channel.
*/
public class DiscardServerHandler extends ChannelHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
// Discard the received data silently.
((ByteBuf) msg).release(); // (3)
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
ctx.close();
}
}
```
- ChannelHandlerAdapter是ChannelHandler的实现类并且为