Netty是一种提供网络编程的工具,是对socket编程的封装,支持TCP、UDP协议,下面用netty实现udp通信。 在java开发中引用netty的优势:支撑nio编程,可以提升并发性能;netty的特性是零拷贝,直接在内存中开辟一块,省去了socket缓冲区;封装完美使得编码简便; netty中channel通道的类型
NioSocketChannel, 代表异步的客户端 TCP Socket 连接.
NioServerSocketChannel, 异步的服务器端 TCP Socket 连接.
NioDatagramChannel, 异步的 UDP 连接
NioSctpChannel, 异步的客户端 Sctp 连接.
NioSctpServerChannel, 异步的 Sctp 服务器端连接.
OioSocketChannel, 同步的客户端 TCP Socket 连接.
OioServerSocketChannel, 同步的服务器端 TCP Socket 连接.
OioDatagramChannel, 同步的 UDP 连接
OioSctpChannel, 同步的 Sctp 服务器端连接.
OioSctpServerChannel, 同步的客户端 TCP Socket 连接
实例
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.58.Final</version>
</dependency>
public class NettyUdpServer {
private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);
/**
* 启动服务
*/
public void init(int port) {
//表示服务器连接监听线程组,专门接受 accept 新的客户端client 连接
EventLoopGroup bossLoopGroup = new NioEventLoopGroup();
try {
//1、创建netty bootstrap 启动类
Bootstrap serverBootstrap = new Bootstrap();
//2、设置boostrap 的eventLoopGroup线程组
serverBootstrap = serverBootstrap.group(bossLoopGroup);
//3、设置NIO UDP连接通道
serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
//4、设置通道参数 SO_BROADCAST广播形式
serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true);
//5、设置处理类 装配流水线
serverBootstrap = serverBootstrap.handler(new NettyUdpHandler());
//6、绑定server,通过调用sync()方法异步阻塞,直到绑定成功
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
logger.info("started and listened on " + channelFuture.channel().localAddress());
//7、监听通道关闭事件,应用程序会一直等待,直到channel关闭
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
} finally {
logger.info("netty udp close!");
//8 关闭EventLoopGroup,
bossLoopGroup.shutdownGracefully();
}
}
}
public class NettyUdpHandler extends SimpleChannelInboundHandler<DatagramPacket> {
private static final Logger logger = LoggerFactory.getLogger(NettyUdpServer.class);
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
try {
ByteBuf byteBuf = packet.content();
String str = byteBuf.toString(CharsetUtil.UTF_8);
logger.info("receive str: " + str);
// res
String resStr = "ok";
byte[] resBytes = resStr.getBytes("UTF-8");
DatagramPacket resData = new DatagramPacket(Unpooled.copiedBuffer(resBytes), packet.sender());
ctx.writeAndFlush(resData);
} catch (Exception e) {
}
}
}
@Component
public class InitTask implements CommandLineRunner {
@Override
public void run(String... args) {
NettyUdpServer nettyUdpServer = new NettyUdpServer();
nettyUdpServer.init(50000);
}
}
通过工具或手写发送端发送数据,接收端即可收到数据。
|