Java Code Examples for io.netty.channel.socket.nio.NioDatagramChannel

The following are top voted examples for showing how to use io.netty.channel.socket.nio.NioDatagramChannel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Nukkit-Java9   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 2
Project: talchain   File: UdpTest.java   Source Code and License 6 votes vote down vote up
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
 
Example 3
Project: Jupiter   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical(FastAppender.get(interfaz, ":", port, " 上でサーバーを開けませんでした。"));
        this.logger.critical("同じポートで複数のサーバーを一度に開いていませんか?");
        System.exit(1);
    }
}
 
Example 4
Project: Jenisys3   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 5
Project: SpringBootStudy   File: UdpServer.java   Source Code and License 6 votes vote down vote up
@Async("myTaskAsyncPool")
public void run(int udpReceivePort) {

    EventLoopGroup group = new NioEventLoopGroup();
    logger.info("Server start!  Udp Receive msg Port:" + udpReceivePort);

    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new UdpServerHandler());   // 设置服务端接收消息的 Handler (保存消息到 mysql 和 redis 中)

        b.bind(udpReceivePort).sync().channel().closeFuture().await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 6
Project: AppCoins-ethereumj   File: UdpTest.java   Source Code and License 6 votes vote down vote up
public Channel create(String bindAddr, int port) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup(1);

    Bootstrap b = new Bootstrap();
    b.group(group)
        .channel(NioDatagramChannel.class)
        .handler(new ChannelInitializer<NioDatagramChannel>() {
            @Override
            public void initChannel(NioDatagramChannel ch)
                    throws Exception {
                ch.pipeline().addLast(new PacketDecoder());
                SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager);
                nodeManager.setMessageSender(messageHandler);
                ch.pipeline().addLast(messageHandler);
            }
        });

    return b.bind(bindAddr, port).sync().channel();
}
 
Example 7
Project: Mods   File: TF2UdpServer.java   Source Code and License 6 votes vote down vote up
public void run() {
	try {
		Bootstrap boot = new Bootstrap();
		boot.group(group)
		 .channel(NioDatagramChannel.class)
		 .handler(new ChannelInitializer<DatagramChannel>() {

			@Override
			protected void initChannel(DatagramChannel ch) throws Exception {
				channel = ch;
				ch.pipeline().addLast(new UdpChannelHandlerServer(TF2UdpServer.this));
			}
			 
		 });
		boot.bind(port).sync().channel().closeFuture();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 8
Project: Mods   File: TF2UdpClient.java   Source Code and License 6 votes vote down vote up
public TF2UdpClient(InetSocketAddress address) throws Exception {
	group = new NioEventLoopGroup();
	this.address = address;
	EntityPlayerSP player = Minecraft.getMinecraft().player;
	Bootstrap boot = new Bootstrap();
	boot.group(group).channel(NioDatagramChannel.class).handler(new UdpChannelHandlerClient());
	
	channel = boot.bind(0).sync().channel();
	
	channel.connect(address);
	
	/*PacketBuffer buffer = new PacketBuffer(Unpooled.buffer());
	buffer.writeShort(playerId);
	buffer.writeShort(0);
	buffer.writeByte(0);
	buffer.writeLong(System.currentTimeMillis());
	
	channel.writeAndFlush(new DatagramPacket(buffer, address));*/
}
 
Example 9
Project: CoreX   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 10
Project: java_learn   File: ChineseProverbClient.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	EventLoopGroup loopGroup = new NioEventLoopGroup();
	try{
		Bootstrap b = new Bootstrap();
		b.group(loopGroup).channel(NioDatagramChannel.class)
		.option(ChannelOption.SO_BROADCAST, true)
		.handler(new ChannelProverbClientHandler());
		Channel ch = b.bind(0).sync().channel();
		//向网段内所有的机器广播UDP消息
		ch.writeAndFlush(
				new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?", CharsetUtil.UTF_8),
				new InetSocketAddress("255.255.255.255", port))).sync();
		//客户端等待15s接受服务端的应答消息,然后退出释放资源
		if(!ch.closeFuture().await(15000)){
			System.out.println("查询超时");
		}
	}finally{
		loopGroup.shutdownGracefully();
	}
	
}
 
Example 11
Project: warp   File: ConnectionService.java   Source Code and License 6 votes vote down vote up
public ConnectionService(SerializedSceneHolder sceneHolder,
                         ClientRemoteEventQueue eventQueue,
                         ComponentRegistry componentRegistry) {

    try {
        Bootstrap b = new Bootstrap();
        ServerConnectionHandler connectionHandler = new ServerConnectionHandler(
                sceneHolder,
                this,
                eventQueue,
                new EventReceiver(componentRegistry));
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(connectionHandler);

        channel = b.bind(0).sync().channel();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 12
Project: jRakNet   File: ClientSocket.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes this socket and binds its internal udp socket to a free port.
 * If the socket is already initialized any invocation of this method will
 * result in an IllegalStateException.
 *
 * @throws SocketException Thrown in case the socket could not be initialized
 */
public void initialize() throws SocketException {
    if ( this.isInitialized() ) {
        throw new IllegalStateException( "Cannot re-initialized ClientSocket" );
    }

    this.udpSocket = new Bootstrap();
    this.udpSocket.group( Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup() );
    this.udpSocket.channel( Epoll.isAvailable() ? EpollDatagramChannel.class : NioDatagramChannel.class );
    this.udpSocket.handler( new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception {
            io.netty.channel.socket.DatagramPacket packet = (io.netty.channel.socket.DatagramPacket) msg;
            PacketBuffer content = new PacketBuffer( packet.content() );
            InetSocketAddress sender = packet.sender();

            if ( !receiveDatagram( sender, content ) ) {
                // Push datagram to update queue:
                handleDatagram( sender, content, System.currentTimeMillis() );
            }
        }
    } );

    try {
        this.channel = this.udpSocket.bind( ThreadLocalRandom.current().nextInt( 45000, 65000 ) ).sync().channel();
    } catch ( InterruptedException e ) {
        SocketException exception = new SocketException( "Could not bind to socket" );
        exception.initCause( e );
        throw exception;
    }

    this.afterInitialize();
}
 
Example 13
Project: Nemisys   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 14
Project: BukkitPE   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (InterruptedException e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("-------------------------------------------------");
        this.logger.critical("There may be another server running on that port!");
        this.logger.critical("--------------------------------------------------");
        System.exit(1);
    }
}
 
Example 15
Project: NukkitGT   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 16
Project: Apollo-OLD   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 17
Project: MagmaBlock   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (InterruptedException e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 18
Project: voxelwind   File: McpeOverRakNetNetworkListener.java   Source Code and License 6 votes vote down vote up
public McpeOverRakNetNetworkListener(VoxelwindServer voxelwindServer, String host, int port, boolean useSoReuseport) {
    this.server = voxelwindServer;
    this.address = new InetSocketAddress(host, port);
    this.useSoReuseport = useSoReuseport;
    if (Epoll.isAvailable()) {
        bootstrap = new Bootstrap()
                .channel(EpollDatagramChannel.class)
                .group(new EpollEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build()))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(this);
        if (useSoReuseport) {
            bootstrap.option(EpollChannelOption.SO_REUSEPORT, true);
        }
    } else {
        bootstrap = new Bootstrap()
                .channel(NioDatagramChannel.class)
                .group(new NioEventLoopGroup(0, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("Voxelwind MCPE Listener - #%d").build()))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .handler(this);
    }
}
 
Example 19
Project: SecureSmartHome   File: UDPDiscoveryServer.java   Source Code and License 6 votes vote down vote up
@Override
public void init(Container container) {
    super.init(container);

    // Acquire lock
    final WifiManager wifi = (WifiManager) requireComponent(ContainerService.KEY_CONTEXT)
            .getSystemService(Context.WIFI_SERVICE);
    multicastLock = wifi.createMulticastLock(getClass().getSimpleName());
    multicastLock.acquire();

    // Setup UDP Channel
    Bootstrap b = new Bootstrap()
            .channel(NioDatagramChannel.class)
            .group(requireComponent(ExecutionServiceComponent.KEY))
            .handler(new RequestHandler())
            .option(ChannelOption.SO_BROADCAST, true);
    channel = b.bind(CoreConstants.NettyConstants.DISCOVERY_SERVER_PORT);
}
 
Example 20
Project: netty-cookbook   File: BootstrapTemplate.java   Source Code and License 6 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example 21
Project: netty-book   File: ChineseProverbClient.java   Source Code and License 6 votes vote down vote up
public void run(int port) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioDatagramChannel.class)
	    .option(ChannelOption.SO_BROADCAST, true)
	    .handler(new ChineseProverbClientHandler());
    Channel ch = b.bind(0).sync().channel();
    // 向网段内的所有机器广播UDP消息
    ch.writeAndFlush(
	    new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?",
		    CharsetUtil.UTF_8), new InetSocketAddress(
		    "255.255.255.255", port))).sync();
    if (!ch.closeFuture().await(15000)) {
	System.out.println("查询超时!");
    }
} finally {
    group.shutdownGracefully();
}
   }
 
Example 22
Project: jfastnet   File: KryoNettyPeer.java   Source Code and License 6 votes vote down vote up
@Override
public boolean start() {
	group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group)
				.channel(NioDatagramChannel.class)
				.option(ChannelOption.SO_BROADCAST, true)
				.option(ChannelOption.SO_SNDBUF, config.socketSendBufferSize)
				.option(ChannelOption.SO_RCVBUF, config.socketReceiveBufferSize)
				.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(config.receiveBufferAllocator))
				.handler(channelHandler != null ? channelHandler : new UdpHandler());

		channel = b.bind(config.bindPort).sync().channel();

	} catch (Exception e) {
		log.error("Couldn't start server.", e);
		return false;
	}
	return true;
}
 
Example 23
Project: Nukkit   File: UDPServerSocket.java   Source Code and License 6 votes vote down vote up
public UDPServerSocket(ThreadedLogger logger, int port, String interfaz) {
    this.logger = logger;
    try {
        bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap
                .group(group)
                .channel(NioDatagramChannel.class)
                .handler(this);
        channel = bootstrap.bind(interfaz, port).sync().channel();
    } catch (Exception e) {
        this.logger.critical("**** FAILED TO BIND TO " + interfaz + ":" + port + "!");
        this.logger.critical("Perhaps a server is already running on that port?");
        System.exit(1);
    }
}
 
Example 24
Project: udp-multiplexer-proxy   File: RtpPartyA.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new RtpPartyAHandler());

        ch = b.bind(36001).sync().channel();

        ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(rtpDataByeArray),
                new InetSocketAddress("127.0.0.1", PORT))).sync();

        if (!ch.closeFuture().await(5000)) {
            Assert.fail("Rtp communication timeout");
        } else {

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 25
Project: DistributedLog4j   File: UDPListener.java   Source Code and License 6 votes vote down vote up
public void activateOptions() throws InterruptedException {

		Bootstrap b = new Bootstrap();
		b.group(group)
			.channel(NioDatagramChannel.class)
			.handler(new Log4jHandler());
		b.option(ChannelOption.SO_REUSEADDR, true);
		b.option(ChannelOption.IP_MULTICAST_IF, MulticastSettings.getIface());
		b.option(ChannelOption.TCP_NODELAY, true);

		InetSocketAddress addr = new InetSocketAddress(MulticastSettings.getAddressToBind(), port);

		b.localAddress(port).remoteAddress(addr);
		ch = (DatagramChannel) b.bind().sync().channel();

		ch.joinGroup(multicastAddress, MulticastSettings.getIface()).sync();
	}
 
Example 26
Project: DistributedLog4j   File: UDPAppender.java   Source Code and License 6 votes vote down vote up
public void activateOptions()  {

		Bootstrap b = new Bootstrap();

		b.group(group)
			.channel(NioDatagramChannel.class);

		b.handler(new Log4jAppenderHandler(port));

		b.option(ChannelOption.IP_MULTICAST_IF, MulticastSettings.getIface());
		b.option(ChannelOption.SO_REUSEADDR, true);
		b.option(ChannelOption.TCP_NODELAY, true);

		InetSocketAddress addr = new InetSocketAddress(MulticastSettings.getAddressToBind(), port);
		b.localAddress(addr);

		try {
			ch = b.bind().sync().channel();
		} catch (InterruptedException e) {
			System.err.println("upd appender error open socket");
		}
	}
 
Example 27
Project: hope-tactical-equipment   File: ChineseProverbClient.java   Source Code and License 6 votes vote down vote up
public void run(int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbClientHandler());
        Channel ch = b.bind(0).sync().channel();
        // 向网段内的所有机器广播UDP消息
        ch.writeAndFlush(
                new DatagramPacket(Unpooled.copiedBuffer("谚语字典查询?",
                        CharsetUtil.UTF_8), new InetSocketAddress(
                        "255.255.255.255", port))).sync();
        if (!ch.closeFuture().await(15000)) {
            System.out.println("查询超时!");
        }
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 28
Project: netty4study   File: QuoteOfTheMomentClient.java   Source Code and License 6 votes vote down vote up
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioDatagramChannel.class)
         .option(ChannelOption.SO_BROADCAST, true)
         .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 29
Project: kume   File: MulticastServerHandler.java   Source Code and License 6 votes vote down vote up
public MulticastServerHandler(Cluster cluster, InetSocketAddress address) throws InterruptedException {
    this.address = address;

    handler = new Bootstrap()
            .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .localAddress(address)
            .group(new NioEventLoopGroup())
            .option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.IP_MULTICAST_IF, multicastInterface)
            .option(ChannelOption.AUTO_READ, false)
            .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                public void initChannel(NioDatagramChannel ch) throws Exception {
                    ch.pipeline().addLast(new MulticastChannelAdapter(cluster));
                }
            });
    localMember = cluster.getLocalMember();
}
 
Example 30
Project: jtftp   File: TftpServer.java   Source Code and License 6 votes vote down vote up
public void run() throws Exception {
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .handler(new ChannelInitializer<DatagramChannel>() {
                    @Override
                    public void initChannel(DatagramChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new LoggingHandler(LogLevel.INFO),
                                new TftpServerHandler());
                    }
                });

        b.bind(port).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 31
Project: distributeTemplate   File: BootstrapFactory.java   Source Code and License 6 votes vote down vote up
public static Bootstrap createUDPBootstrap(final ChannelType channelType) throws UnsupportedOperationException {
    Bootstrap bootstrap = new Bootstrap();

    switch (channelType) {
        case NIO:
        	
            bootstrap.group(new NioEventLoopGroup());
            bootstrap.channel(NioDatagramChannel.class);
            return bootstrap;

        case OIO:
        	
            bootstrap.group(new OioEventLoopGroup());
            bootstrap.channel(OioDatagramChannel.class);
            return bootstrap;

        default:
            throw new UnsupportedOperationException("Failed to create Bootstrap,  " + channelType + " not supported!");
    }
}
 
Example 32
Project: distributeTemplate   File: ServerUDPBootstrapFactory.java   Source Code and License 6 votes vote down vote up
public static Bootstrap createServerBootstrap(final ChannelType channelType) throws UnsupportedOperationException {
    
	Bootstrap serverBootstrap = new Bootstrap();

    switch (channelType) {
        case NIO:
            serverBootstrap.group(new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()));
            serverBootstrap.channel(NioDatagramChannel.class);
           // serverBootstrap.localAddress(new InetSocketAddress(port))
           // .handler(packetHandler);
          
            return serverBootstrap;

        case OIO:
        	 serverBootstrap.group(new OioEventLoopGroup(Runtime.getRuntime().availableProcessors()));
             serverBootstrap.channel(OioDatagramChannel.class);
          
            
            return serverBootstrap;

        default:
            throw new UnsupportedOperationException("Failed to create ServerBootstrap,  " + channelType + " not supported!");
    }
}
 
Example 33
Project: netty-netty-5.0.0.Alpha1   File: QuoteOfTheMomentClient.java   Source Code and License 6 votes vote down vote up
public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioDatagramChannel.class)
         .option(ChannelOption.SO_BROADCAST, true)
         .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 34
Project: whale   File: IotNettyService.java   Source Code and License 6 votes vote down vote up
public void init() throws InterruptedException {
	if (tcpPort == 0 && udpPort == 0) {
		log.info("tcpPort=0 and udpPort=0, socket proctol disable");
		return;
	}
	bossGroup = new NioEventLoopGroup(2);
	workerGroup = new NioEventLoopGroup();
	udpWorkGroup = new NioEventLoopGroup();
	if (tcpPort > 0) {
		tcpBoot = new ServerBootstrap();
		tcpBoot.group(bossGroup, workerGroup)
				.channel(NioServerSocketChannel.class)
				.handler(new LoggingHandler(LogLevel.INFO))
				.childHandler(iotNettyTcpServerInitializer);
		tcpcf = tcpBoot.bind(tcpPort);
	}
	if (udpPort > 0) {
		udpBoot = new Bootstrap();
		udpBoot.group(udpWorkGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(iotNettyUdpHandler);
		udpcf = udpBoot.bind(udpPort);
	}
}
 
Example 35
Project: sipstack   File: UAS.java   Source Code and License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final UAS uas = new UAS();
    final EventLoopGroup udpGroup = new NioEventLoopGroup();

    final Bootstrap b = new Bootstrap();
    b.group(udpGroup)
    .channel(NioDatagramChannel.class)
    .handler(new ChannelInitializer<DatagramChannel>() {
        @Override
        protected void initChannel(final DatagramChannel ch) throws Exception {
            final ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("decoder", new SipMessageDatagramDecoder());
            pipeline.addLast("encoder", new SipMessageEncoder());
            pipeline.addLast("handler", uas);
        }
    });

    final InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 5060);
    b.bind(socketAddress).sync().channel().closeFuture().await();
}
 
Example 36
Project: tomp2p_5   File: ChannelServer.java   Source Code and License 6 votes vote down vote up
/**
 * Start to listen on a UPD port.
 * 
 * @param listenAddresses
 *            The address to listen to
 * @param config
 *            Can create handlers to be attached to this port
 * @return True if startup was successful
 */
boolean startupUDP(final InetSocketAddress listenAddresses, final ChannelServerConficuration config) {
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioDatagramChannel.class);
    b.option(ChannelOption.SO_BROADCAST, true);
    b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(ConnectionBean.UDP_LIMIT));

    b.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            for (Map.Entry<String, ChannelHandler> entry : handlers(false).entrySet()) {
                ch.pipeline().addLast(entry.getKey(), entry.getValue());
            }
        }
    });

    ChannelFuture future = b.bind(listenAddresses);
    channelUDP = future.channel();
    return handleFuture(future);
}
 
Example 37
Project: logstash-gelf   File: WildFlyHandlerIntegrationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testGelfSubmissionToEmbeddedNettyGelfServer() throws Exception {
    NettyLocalServer nettyLocalServer = new NettyLocalServer(NioDatagramChannel.class);
    nettyLocalServer.run();
    String logMessage = "some log event";

    int iterations = 0;
    while (nettyLocalServer.getJsonValues().isEmpty() && iterations < 10) {
        LogManager.getLogger(getClass()).info(logMessage);
        Thread.sleep(100);
        iterations++;
    }

    assertThat(nettyLocalServer.getJsonValues()).isNotEmpty();

    boolean foundSomeLogEvent = false;

    for (Object o : nettyLocalServer.getJsonValues()) {
        if (o.toString().contains(logMessage)) {
            foundSomeLogEvent = true;
        }
    }
    assertThat(foundSomeLogEvent).isTrue();
    nettyLocalServer.close();
}
 
Example 38
Project: jts-tanks   File: GameServer.java   Source Code and License 6 votes vote down vote up
public static void startNetworkServer() {
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.option(ChannelOption.SO_BROADCAST, true);
	bootstrap.channel(NioDatagramChannel.class).handler(new Game2ClientChannelHandler());

	String host = GameServerProperty.getInstance().GAME_CLIENT_HOST;
	int port = GameServerProperty.getInstance().GAME_CLIENT_PORT;
	if (host.equals("*")) {
		bootstrap.localAddress(port);
	} else {
		bootstrap.localAddress(host, port);
	}

	NetworkThread clientsNetworkThread = new NetworkThread(bootstrap, true);

	clientsNetworkThread.start();

	log.info("Clients NetworkThread loaded on {}:{}", host, port);
}
 
Example 39
Project: sbrw-freeroam-srv   File: NettyUdpServer.java   Source Code and License 5 votes vote down vote up
public ChannelFuture start() throws InterruptedException {
	workerGroup = new NioEventLoopGroup();

	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(workerGroup).channel(NioDatagramChannel.class).handler(new ServerChannelInitializer());

	ChannelFuture channelFuture = bootstrap.bind(new InetSocketAddress(port)).syncUninterruptibly();
	channel = channelFuture.channel();

	return channelFuture;
}
 
Example 40
Project: rskj   File: UDPServer.java   Source Code and License 5 votes vote down vote up
private Bootstrap createBootstrap(EventLoopGroup group) {
    return new Bootstrap().group(group).channel(NioDatagramChannel.class)
            .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                public void initChannel(NioDatagramChannel ch)
                        throws Exception {
                    ch.pipeline().addLast(new PacketDecoder());
                    UDPChannel udpChannel = new UDPChannel(ch, peerExplorer);
                    peerExplorer.setUDPChannel(udpChannel);
                    ch.pipeline().addLast(udpChannel);
                }
            });
}
 
Example 41
Project: nearenough   File: NettyClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, NoSuchAlgorithmException {
  InetSocketAddress addr = new InetSocketAddress(GOOGLE_SERVER_HOST, GOOGLE_SERVER_PORT);

  System.out.printf("Sending request to %s\n", addr);

  // Below is Netty boilerplate for setting-up an event loop and registering a handler

  NioEventLoopGroup group = new NioEventLoopGroup();
  Bootstrap bootstrap = new Bootstrap()
      .group(group)
      .remoteAddress(addr)
      .channel(NioDatagramChannel.class)
      .handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) throws Exception {
          ch.pipeline()
              .addLast(new ReadTimeoutHandler(5))
              .addLast(new RequestHandler(addr));
        }
      });

  ChannelFuture connectFuture = bootstrap.connect();
  connectFuture.addListener(fut -> {
    if (!fut.isSuccess()) {
      System.out.println("Connect fail:");
      System.out.println(fut.cause().getMessage());
    }
  });

  connectFuture.channel().closeFuture().sync();
  group.shutdownGracefully();
}
 
Example 42
Project: SpringBootStudy   File: UdpClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpClientHandler());

            Channel ch = b.bind(0).sync().channel();

            String UdpMsg = "this a message form client !";

            logger.info("Client ===> : {}", UdpMsg);

            // Broadcast the QOTM request to port 8880.
            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer(UdpMsg, CharsetUtil.UTF_8),
                    SocketUtils.socketAddress("localhost", PORT))).sync();

            // UdpClientHandler 接收到服务器响应的消息时,会关闭 DatagramChannel (数据报通道)
            // 如果 DatagramChannel (数据报通道) 没有在 5秒内关闭,那么打印错误日志,并退出
            if (!ch.closeFuture().await(5000)) {
                logger.error("Server response timed out.");
            }
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 43
Project: lippen-network-tool   File: NetUDPServer.java   Source Code and License 5 votes vote down vote up
public NetUDPServer(DataManager data, MessageReceivedListener listener) {
	super(data, "UDP");
	b = new Bootstrap();
	EventLoopGroup group = new NioEventLoopGroup();
	b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
			.handler(new UDPHandler(data, listener));
}
 
Example 44
Project: java_learn   File: ChineseProverbServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	EventLoopGroup loopGroup = new NioEventLoopGroup();
	try{
		Bootstrap b = new Bootstrap();
		b.group(loopGroup).channel(NioDatagramChannel.class)
		.option(ChannelOption.SO_BROADCAST, true)
		.handler(new ChannelProverbServerHandler());
		ChannelFuture f = b.bind(port).sync();
		f.channel().closeFuture().sync();
	}finally{
		loopGroup.shutdownGracefully();
	}
	
}
 
Example 45
Project: warp   File: ServerTask.java   Source Code and License 5 votes vote down vote up
@Override
protected void onInit() {
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ConnectionHandler(clientRegistry, connectionUtil, componentRegistry));
        outChannel = b.bind(PORT).sync().channel();
        connectionUtil.setOutChannel(outChannel);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 46
Project: mpush   File: NettyUDPConnector.java   Source Code and License 5 votes vote down vote up
private void createNioServer(Listener listener) {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(
            1, new DefaultThreadFactory(ThreadNames.T_GATEWAY_WORKER)
    );
    eventLoopGroup.setIoRatio(100);
    createServer(listener, eventLoopGroup, () -> new NioDatagramChannel(IPv4));//默认是根据机器情况创建Channel,如果机器支持ipv6,则无法使用ipv4的地址加入组播
}
 
Example 47
Project: PocketServer   File: PipelineUtil.java   Source Code and License 5 votes vote down vote up
public static Class<? extends Channel> getChannelClass() {
    if (useEpoll) {
        return EpollDatagramChannel.class;
    } else {
        return NioDatagramChannel.class;
    }
}
 
Example 48
Project: Controller-Support   File: DaemonManager.java   Source Code and License 5 votes vote down vote up
public static InvocationManager startDaemon() throws Exception {
	int port = findFreePort();
	String javaHome = System.getProperty("java.home");
	String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
	String classpath = System.getProperty("java.class.path");
	String libPath = "-Djava.library.path=" + System.getProperty("java.library.path");
	String className = DaemonMain.class.getCanonicalName();
	String args = Config.INSTANCE.shouldDebugInput() ? "debugControllerInput" : "";

	ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, libPath, className, String.valueOf(port), args);
	builder.inheritIO();

	process = builder.start();
	Thread.sleep(2000);//Waiting for Daemon to start.
	
	ClientNetworkHandler cnw = new ClientNetworkHandler();
	InetSocketAddress adr = new InetSocketAddress("localhost", port);
	
	Bootstrap b = new Bootstrap();
	b.group(new NioEventLoopGroup());
	b.channel(NioDatagramChannel.class);
	b.handler(cnw);
	ChannelFuture future = b.connect(adr).syncUninterruptibly();
	
	cnw.init(future.channel(), adr);
	InvocationManager manager = new InvocationManager(cnw);
	cnw.setInvocationManager(manager);
	manager.init();
	
	Thread t = new Thread(() -> {
		future.channel().closeFuture().syncUninterruptibly();
		b.group().shutdownGracefully();
	});
	t.setDaemon(true);
	t.setName("Netty-IPC Shutdown Waiter");
	
	Runtime.getRuntime().addShutdownHook(new Thread(() -> stopDaemon()));
	
	return manager;
}
 
Example 49
Project: study-netty   File: LogEventMonitor.java   Source Code and License 5 votes vote down vote up
public LogEventMonitor(InetSocketAddress address) {
	group = new NioEventLoopGroup();
	bootstrap = new Bootstrap();
	bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
			.handler(new ChannelInitializer<Channel>() {
				protected void initChannel(Channel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(new LogEventDecoder());
					pipeline.addLast(new LogEventHandler());
				}
			}).localAddress(address);
}
 
Example 50
Project: study-netty   File: LogEventBroadcaster.java   Source Code and License 5 votes vote down vote up
public LogEventBroadcaster(InetSocketAddress address, File file) {
	group = new NioEventLoopGroup();
	bootstrap = new Bootstrap();
	bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
			.handler(new LogEventEncoder(address));
	this.file = file;
}
 
Example 51
Project: incubator-pulsar   File: EventLoopUtil.java   Source Code and License 5 votes vote down vote up
public static Class<? extends DatagramChannel> getDatagramChannelClass(EventLoopGroup eventLoopGroup) {
    if (eventLoopGroup instanceof EpollEventLoopGroup) {
        return EpollDatagramChannel.class;
    } else {
        return NioDatagramChannel.class;
    }
}
 
Example 52
Project: async-gamequery-lib   File: SourceLogListenService.java   Source Code and License 5 votes vote down vote up
/**
 * <p>Creates a new service using the specified {@link InetSocketAddress} to listen on and utilizing
 * the callback specified to notify listeners of source log events</p>
 *
 * @param listenAddress
 *         An {@link InetSocketAddress} where the listen service will bind or listen on
 * @param logEventCallback
 *         A {@link Consumer} callback that will be called once a log event has been received
 */
public SourceLogListenService(InetSocketAddress listenAddress, Consumer<SourceLogEntry> logEventCallback) {
    this.listenAddress = listenAddress;
    bootstrap = new Bootstrap()
            .localAddress(this.listenAddress)
            .channel(NioDatagramChannel.class)
            .group(listenWorkGroup)
            .handler(new ChannelInitializer<NioDatagramChannel>() {
                @Override
                protected void initChannel(NioDatagramChannel ch) throws Exception {
                    ch.pipeline().addLast(new SourceLogListenHandler(logEventCallback));
                }
            });

    SourceLogListenService service = this;
    //Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                log.debug("Service Interrupted. Shutting down gracefully.");
                service.shutdown();
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }
    });
}
 
Example 53
Project: async-gamequery-lib   File: NettyBasicUdpTransport.java   Source Code and License 5 votes vote down vote up
public NettyBasicUdpTransport(ChannelType channelType) {
    super(channelType);
    NettyTransport transport = this;
    getBootstrap().handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) throws Exception {
            getChannelInitializer().initializeChannel(ch, transport);
        }
    });
}
 
Example 54
Project: reactor-netty   File: ClientOptions.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
final void groupAndChannel(Bootstrap bootstrap) {
	LoopResources loops = Objects.requireNonNull(getLoopResources(), "loopResources");

	boolean useNative =
			this.protocolFamily == null && preferNative() && !(sslContext() instanceof JdkSslContext);
	EventLoopGroup elg = loops.onClient(useNative);

	if (this.poolResources != null && elg instanceof Supplier) {
		//don't colocate
		bootstrap.group(((Supplier<EventLoopGroup>) elg).get());
	}
	else {
		bootstrap.group(elg);
	}

	if (useDatagramChannel()) {
		if (useNative) {
			bootstrap.channel(loops.onDatagramChannel(elg));
		}
		else {
			bootstrap.channelFactory(() -> new NioDatagramChannel(protocolFamily));
		}
	}
	else {
		bootstrap.channel(loops.onChannel(elg));
	}
}
 
Example 55
Project: JavaAyo   File: QuoteOfTheMomentServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioDatagramChannel.class)
         .option(ChannelOption.SO_BROADCAST, true)
         .handler(new QuoteOfTheMomentServerHandler());

        b.bind(PORT).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 56
Project: JavaAyo   File: QuoteOfTheMomentClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BROADCAST, true)
             .handler(new QuoteOfTheMomentClientHandler());

            Channel ch = b.bind(0).sync().channel();

            // Broadcast the QOTM request to port 8080.
            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                    new InetSocketAddress("255.255.255.255", PORT))).sync();

            // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
            // response is received.  If the channel is not closed within 5 seconds,
            // print an error message and quit.
            if (!ch.closeFuture().await(5000)) {
                System.err.println("QOTM request timed out.");
            }
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 57
Project: SecureSmartHome   File: UDPDiscoveryClient.java   Source Code and License 5 votes vote down vote up
/**
 * Start discovery if it is not running yet and send the first discovery request.
 */
public void startDiscovery(long timeout) {
    if (this.timeout > 0 && timeout > 0) {
        this.timeout = Math.max(this.timeout, System.currentTimeMillis() + timeout);
    } else if (timeout > 0) {
        this.timeout = System.currentTimeMillis() + timeout;
    } else {
        this.timeout = 0;
    }
    Log.i(TAG, "startDiscovery, " + (isDiscoveryRunning ? "already" : "currently not") + " running with timeout " + timeout);
    if (!isDiscoveryRunning) {
        isDiscoveryRunning = true;

        // Acquire lock
        if (multicastLock == null) {
            final WifiManager wifi = (WifiManager) requireComponent(ContainerService.KEY_CONTEXT)
                    .getSystemService(Context.WIFI_SERVICE);
            multicastLock = wifi.createMulticastLock(getClass().getSimpleName());
            multicastLock.setReferenceCounted(false);
        }
        multicastLock.acquire();

        // Setup UDP Channel
        if (channel == null) {
            Bootstrap b = new Bootstrap()
                    .channel(NioDatagramChannel.class)
                    .group(requireComponent(ExecutionServiceComponent.KEY))
                    .handler(new ResponseHandler())
                    .option(ChannelOption.SO_BROADCAST, true);
            channel = b.bind(0);
        }

        sendDiscoveryRequest();
        scheduleDiscoveryRetry();
    }
}
 
Example 58
Project: netty-cookbook   File: BootstrapTemplate.java   Source Code and License 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example 59
Project: netty-cookbook   File: BootstrapTemplate.java   Source Code and License 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}
 
Example 60
Project: netty-cookbook   File: BootstrapTemplate.java   Source Code and License 5 votes vote down vote up
public static ChannelFuture newBootstrapUDP(EventLoopGroup loopGroup, SimpleChannelInboundHandler<DatagramPacket> handler, int port){
	return new Bootstrap().group(loopGroup)
			.channel(NioDatagramChannel.class)
			.option(ChannelOption.SO_BROADCAST, true)
			.handler(handler)
			.bind(port);
}