spirngboot使用netty實現UDP協議接收數據


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();

	}

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM