52 lines
1.7 KiB
Java
52 lines
1.7 KiB
Java
package com.zhgd.netty.udp;
|
||
|
||
import io.netty.bootstrap.Bootstrap;
|
||
import io.netty.channel.Channel;
|
||
import io.netty.channel.ChannelInitializer;
|
||
import io.netty.channel.ChannelOption;
|
||
import io.netty.channel.EventLoopGroup;
|
||
import io.netty.channel.nio.NioEventLoopGroup;
|
||
import io.netty.channel.socket.nio.NioDatagramChannel;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
import javax.annotation.PostConstruct;
|
||
|
||
@Component
|
||
@Slf4j
|
||
public class UDPServerApp {
|
||
@Autowired
|
||
private UDPServerHandler udpServerHandler;
|
||
|
||
@Value("${udp.port:}")
|
||
private Integer port;
|
||
|
||
@PostConstruct
|
||
public void startUdpApp() {
|
||
if (port == null) {
|
||
return;
|
||
}
|
||
log.info("启动udp中……");
|
||
Bootstrap bootstrap = new Bootstrap();
|
||
EventLoopGroup workGroup = new NioEventLoopGroup();
|
||
bootstrap.group(workGroup).channel(NioDatagramChannel.class)
|
||
.option(ChannelOption.SO_BROADCAST, true)
|
||
.handler(new ChannelInitializer<NioDatagramChannel>() {
|
||
|
||
@Override
|
||
protected void initChannel(NioDatagramChannel ch) throws Exception {
|
||
ch.pipeline().addLast(udpServerHandler);
|
||
}
|
||
});
|
||
try {
|
||
Channel channel = bootstrap.bind(port).sync().channel();
|
||
//channel.closeFuture().sync().await();
|
||
log.info("启动udp成功,端口:{}", port);
|
||
} catch (Exception e) {
|
||
log.error("udp启动err:", e);
|
||
}
|
||
}
|
||
}
|