Maven 引入
<!-- netty依赖 springboot2.x自动导入版本 -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<!-- 这里我用到了@slf4j 所以引入这个jar -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
初始化服务
/**
* @author
*/
@Slf4j
public class BootNettyUdpServer {
/**
* 启动服务
*/
public void bind(int port) {
System.out.println("-------------------------------udpServer-------------------------!");
log.error("-------------------------------udpServer-------------------------");
//表示服务器连接监听线程组,专门接受 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 BootNettyUdpSimpleChannelInboundHandler());
//6、绑定server,通过调用sync()方法异步阻塞,直到绑定成功
ChannelFuture f = serverBootstrap.bind(port).sync();
log.error(BootNettyUdpServer.class.getName()+" started and listend on "+f.channel().localAddress());
//7、监听通道关闭事件,应用程序会一直等待,直到channel关闭
f.channel().closeFuture().sync();
} catch (Exception e) {
// TODO: handle exception
} finally {
System.out.println("netty udp close!");
//8 关闭EventLoopGroup,
bossLoopGroup.shutdownGracefully();
}
}
}
接收数据
/**
* @author
*/
@Slf4j
public class BootNettyUdpSimpleChannelInboundHandler extends SimpleChannelInboundHandler<DatagramPacket> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
try {
// 读取数据
ByteBuf byteBuf = packet.content();
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
System.out.println("receive client msg:" + new String(bytes));
String test = "0020A5A500000000";
byte[] resBytes = test.getBytes();
DatagramPacket sendPacket = new DatagramPacket(Unpooled.copiedBuffer(resBytes), packet.sender());
ctx.writeAndFlush(sendPacket);
} catch (Exception e) {
}
}
}
启动服务
@SpringBootApplication
@EnableAsync
public class UdpApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(UdpApplication.class);
//启动服务
new BootNettyUdpServer().bind(51880);
}
}