netty udp协议 硬件对接发送数据
- 创建UDP服务
@Component
@Slf4j
@Order(5)
public class NettyUdpStart implements ApplicationRunner {
/**
* 启动netty服务
*
* @throws InterruptedException
*/
private Bootstrap b;
private EventLoopGroup bossGroup = null;
private Channel channel;
private Integer port;
public void start() {
if(SpringInitRunner.serverConfigDTOHashMap.get(ServerTypeEnum.TALKBACK_TERMINALS.getId())!=null){
port=SpringInitRunner.serverConfigDTOHashMap.get(ServerTypeEnum.TALKBACK_TERMINALS.getId()).getPort();
}else {
return;
}
b = new Bootstrap();
bossGroup = new NioEventLoopGroup(4);
try {
NetworkInterface ni = NetUtil.LOOPBACK_IF;
InetAddress localAddress = null;
localAddress=InetAddress.getByName(SpringInitRunner.fileDTO.getDefaultIP());
b.group(bossGroup)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
// 设置LocalAddress
.localAddress(localAddress, port)
// 设置读缓冲区为 10M
.option(ChannelOption.SO_RCVBUF, 1024 * 1024 * 10)
// 设置写缓冲区为1M
.option(ChannelOption.SO_SNDBUF, 1024 * 1024 * 10)
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
ChannelPipeline pipeline = nioDatagramChannel.pipeline();
pipeline.addLast(bossGroup, new UdpServerHandler());
}
});
//开启需要监听 的端口
ChannelFuture sync = b.bind(0);
this.channel=sync.channel();
log.info("启动成功:{}",port);
} catch (Exception e) {
log.error("启动异常", e);
} finally {
// bossGroup.shutdownGracefully();
}
}
public void stop() {
try {
if (channel != null) {
log.info("udp server is stopping listen port {} ...", port);
channel.close();
channel = null;
log.info("udp server is stopped to listen port {} !", port);
}
} catch (Exception e) {
log.error("close netty udp server exception", e);
}
}
@Override
public void run(ApplicationArguments args) throws Exception {
start();
}
}
- UdpServerHandler
@Component
@ChannelHandler.Sharable
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
// 将接收到的数据转为字符串,此字符串就是客户端发送的字符串
ByteBuf buf = msg.content();
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String receiveStr = ConvertCode.receiveHexToString(bytes);
System.err.println("客户端接收到消息:" + receiveStr);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}