compile group: 'io.netty', name: 'netty-all', version: '4.1.42.Final'
package com.test.udp; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioDatagramChannel; public class NettyServer { private final int port; public NettyServer(int port) { this.port = port; } public void start() throws Exception { EventLoopGroup bossGroup=new NioEventLoopGroup(); try { //通過NioDatagramChannel創建Channel,並設置Socket參數支持廣播 //UDP相對於TCP不需要在客戶端和服務端建立實際的連接,因此不需要為連接(ChannelPipeline)設置handler Bootstrap b=new Bootstrap(); b.group(bossGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ServerHandler()); b.bind(port).sync().channel().closeFuture().await(); } catch (Exception e) { e.printStackTrace(); } finally{ bossGroup.shutdownGracefully(); } } }
啟動類
public class ThumbnailServiceApplication { public static void main(String[] args) throws Exception { SpringApplication.run(ThumbnailServiceApplication.class, args); new NettyServer(12345).start(); } }