@Slf4j
@Component
public class NettyUdpClient {
@Autowired
private PropertyUtils propertyUtils;
@Autowired
private NettyUdpClientHandler nettyClientHandler;
private EventLoopGroup group;
private Bootstrap b;
private ChannelFuture cf;
@Bean
public void startUdpClient() {
group = new NioEventLoopGroup();
b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel ch) throws Exception {
// TODO Auto-generated method stub
ChannelPipeline pipeline = ch.pipeline();
//自定义Handler
pipeline.addLast(nettyClientHandler);
}
});
}
public void connect() {
try {
this.cf = b.connect(propertyUtils.getNettyUdpIp(), propertyUtils.getNettyUdpPort()).sync();
} catch (InterruptedException e) {
log.error("客户端连接服务端异常:" + e);
}
}
public ChannelFuture getChannelFuture() {
if (this.cf == null) {
this.connect();
}
if (!this.cf.channel().isActive()) {
this.connect();
}
return this.cf;
}
public void close() {
try {
this.cf.channel().closeFuture().sync();
this.group.shutdownGracefully();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sendMessage(String msg) throws InterruptedException {
ChannelFuture cf = this.getChannelFuture();
cf.channel().writeAndFlush(msg);
}
}
@Slf4j
@Configuration
public class NettyUdpClientHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) {
log.info("ClientHandler Active");
}
/**
* @param ctx
* @author xiongchuan on 2019/4/28 16:10
* @DESCRIPTION: 有服务端端终止连接服务器会触发此函数
* @return: void
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) {
ctx.close();
log.info("服务端终止了服务");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
DatagramPacket datagramPacket = (DatagramPacket) msg;
ByteBuf byteBuf = datagramPacket.content();
log.info("回写数据:" + byteBuf.toString(CharsetUtil.UTF_8));
byteBuf.clear();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//cause.printStackTrace();
log.info("服务端发生异常【" + cause.getMessage() + "】");
ctx.close();
}
/**
* @param msg 需要发送的消息内容
* @param channelId 连接通道唯一id
* @author xiongchuan on 2019/4/28 16:10
* @DESCRIPTION: 客户端给服务端发送消息
* @return: void
*/
public void channelWrite(Channel channel, String msg) {
ByteBuf byteBuf=Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
channel.writeAndFlush(byteBuf);
}
/**
* 向netty服务端发送消息
*/
@GetMapping("udp")
public String udp() {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//nettyTcpClient.sendMessage("发送入网检测认证消息:" + df.format(new Date()));
ChannelFuture channelFuture=nettyUdpClient.getChannelFuture();
Channel channel=channelFuture.channel();
nettyUdpClientHandler.channelWrite(channel, "发送终端检测认证消息:" + df.format(new Date()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "UDP-success";
}