package com.genersoft.iot.vmp.netty.handle;
|
|
import io.netty.buffer.ByteBuf;
|
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.SimpleChannelInboundHandler;
|
import io.netty.channel.socket.DatagramPacket;
|
import io.netty.util.CharsetUtil;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.stereotype.Component;
|
|
/**
|
* updHandler udp 服务端数据接收处理
|
* @author zhongrj
|
* @date 2023-02-21
|
*/
|
@Component
|
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
|
private Logger logger = LoggerFactory.getLogger(this.getClass());
|
|
@Override
|
protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
|
// 读取收到的数据
|
ByteBuf buf = (ByteBuf) datagramPacket.copy().content();
|
byte[] req = new byte[buf.readableBytes()];
|
buf.readBytes(req);
|
String body = new String(req, CharsetUtil.UTF_8);
|
System.out.println("【UDP】>>>>>> 收到客户端的数据:"+body);
|
//获取字符串的长度
|
int length = body.length();
|
System.out.println("数据长度>>>>>> = " + length);
|
}
|
|
//捕获异常
|
@Override
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
|
logger.error("UdpServerHandler exceptionCaught"+cause.getMessage());
|
System.out.println("UdpServerHandler exceptionCaught"+cause.getMessage());
|
cause.printStackTrace();
|
ctx.close();
|
}
|
|
//消息没有结束的时候触发
|
@Override
|
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
|
ctx.flush();
|
}
|
}
|