Example usage for io.netty.channel ChannelOption SO_BROADCAST

List of usage examples for io.netty.channel ChannelOption SO_BROADCAST

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_BROADCAST.

Prototype

ChannelOption SO_BROADCAST

To view the source code for io.netty.channel ChannelOption SO_BROADCAST.

Click Source Link

Usage

From source file:com.jjzhk.Chapter12.udp.ChineseProverbClient.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//  w w w  . j a  va  2 s . c o  m
        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();
        // ???????DP
        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();
    }
}

From source file:com.liferay.sync.engine.lan.server.discovery.LanDiscoveryBroadcaster.java

License:Open Source License

private void _initialize() throws Exception {
    _eventLoopGroup = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioDatagramChannel.class);
    bootstrap.group(_eventLoopGroup);// w ww . j  av a 2 s .  c o  m
    bootstrap.handler(new LanDiscoveryBroadcasterHandler());
    bootstrap.option(ChannelOption.SO_BROADCAST, true);

    ChannelFuture channelFuture = bootstrap.bind(0);

    try {
        channelFuture = channelFuture.sync();

        _channel = channelFuture.channel();
    } catch (InterruptedException ie) {
        _eventLoopGroup.shutdownGracefully();

        throw ie;
    }
}

From source file:com.lunex.inputprocessor.testdemo.QuoteOfTheMomentClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {// ww  w.  j a  v a2s.  c o m
        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();
    }
}

From source file:com.marphain.demo.communication.netty.UDPServer.java

License:Apache License

public void run() throws Exception {
    //number of threads is 8.
    EventLoopGroup group = new NioEventLoopGroup(8);

    try {/*  w ww.  j a  va2s  .c  o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, false)
                .option(ChannelOption.SO_RCVBUF, REMSIZE * 200).handler(new UDPServerHandler());

        b.bind(port).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.mpush.netty.udp.NettyUDPConnector.java

License:Apache License

private void createServer(Listener listener, EventLoopGroup eventLoopGroup,
        ChannelFactory<? extends DatagramChannel> channelFactory) {
    this.eventLoopGroup = eventLoopGroup;
    try {/*from  w ww  .j ava 2 s  . co m*/
        Bootstrap b = new Bootstrap();
        b.group(eventLoopGroup)//?Channel,?ipv6,ipv4?
                .channelFactory(channelFactory).option(ChannelOption.SO_BROADCAST, true)
                .handler(getChannelHandler());

        initOptions(b);

        //???host???
        b.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                logger.info("udp server start success on:{}", port);
                if (listener != null)
                    listener.onSuccess(port);
            } else {
                logger.error("udp server start failure on:{}", port, future.cause());
                if (listener != null)
                    listener.onFailure(future.cause());
            }
        });
    } catch (Exception e) {
        logger.error("udp server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("udp server start exception, port=" + port, e);
    }
}

From source file:com.sp.ReliaableUdpServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from   w  w  w . j av a  2 s.c om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new UdpHandler());

        b.bind(PORT).sync().channel().closeFuture().await();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.spotify.heroic.consumer.collectd.Server.java

License:Apache License

public static AsyncFuture<Server> setup(final AsyncFramework async, final CollectdChannelHandler handler,
        final InetAddress host, final int port) {
    final EventLoopGroup group = new NioEventLoopGroup();
    final Bootstrap b = new Bootstrap();

    b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(handler);

    final ResolvableFuture<Server> future = async.future();

    b.bind(host, port).addListener(new ChannelFutureListener() {
        @Override//from ww  w  .  j  ava2 s .c o  m
        public void operationComplete(final ChannelFuture f) throws Exception {
            if (f.isSuccess()) {
                future.resolve(new Server(async, f.channel()));
            } else {
                future.fail(f.cause() != null ? f.cause() : new RuntimeException("Failed to bind"));
            }
        }
    });

    return future;
}

From source file:com.whirvis.jraknet.client.RakNetClient.java

License:Open Source License

/**
 * Connects the client to a server./*from w w  w . ja v  a 2 s.c  om*/
 * 
 * @param address
 *            the address of the server to connect to.
 * @throws NullPointerException
 *             if the <code>address</code> or the IP address of the
 *             <code>address</code> is <code>null</code>.
 * @throws IllegalStateException
 *             if the client is currently connected to a server.
 * @throws RakNetException
 *             if an error occurs during connection or login.
 */
public void connect(InetSocketAddress address)
        throws NullPointerException, IllegalStateException, RakNetException {
    if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    } else if (this.isConnected()) {
        throw new IllegalStateException("Client is currently connected to a server");
    } else if (listeners.isEmpty()) {
        log.warn("Client has no listeners");
    }

    // Initiate networking
    this.serverAddress = address;
    try {
        this.bootstrap = new Bootstrap();
        this.group = new NioEventLoopGroup();
        this.handler = new RakNetClientHandler(this);
        bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
        this.channel = (bindingAddress != null ? bootstrap.bind(bindingAddress) : bootstrap.bind(0)).sync()
                .channel();
        this.bindAddress = (InetSocketAddress) channel.localAddress();
        this.setMaximumTransferUnitSizes(DEFAULT_TRANSFER_UNIT_SIZES);
        log.debug("Initialized networking");
    } catch (InterruptedException e) {
        throw new RakNetException(e);
    }

    // Prepare connection
    MaximumTransferUnit[] units = MaximumTransferUnit.sort(maximumTransferUnits);
    for (MaximumTransferUnit unit : maximumTransferUnits) {
        unit.reset();
        log.debug("Reset maximum transfer unit with size of " + unit.getSize() + " bytes ("
                + (unit.getSize() * 8) + " bits)");
    }
    this.peerFactory = new PeerFactory(this, address, bootstrap, channel, units[0].getSize(),
            highestMaximumTransferUnitSize);
    log.debug("Reset maximum transfer units and created peer peerFactory");
    peerFactory.startAssembly(units);

    // Send connection packet
    ConnectionRequest connectionRequest = new ConnectionRequest();
    connectionRequest.clientGuid = this.guid;
    connectionRequest.timestamp = System.currentTimeMillis() - timestamp;
    connectionRequest.encode();
    peer.sendMessage(Reliability.RELIABLE_ORDERED, connectionRequest);
    log.debug("Sent connection request to server");

    // Create and start peer update thread
    RakNetClient client = this;
    this.peerThread = new Thread(
            RakNetClient.class.getSimpleName() + "-Peer-Thread-" + Long.toHexString(guid).toUpperCase()) {

        @Override
        public void run() {
            while (peer != null && !this.isInterrupted()) {
                try {
                    Thread.sleep(0, 1); // Lower CPU usage
                } catch (InterruptedException e) {
                    this.interrupt(); // Interrupted during sleep
                    continue;
                }
                if (peer != null) {
                    if (!peer.isDisconnected()) {
                        try {
                            peer.update();
                        } catch (Throwable throwable) {
                            client.callEvent(listener -> listener.onPeerException(client, peer, throwable));
                            if (!peer.isDisconnected()) {
                                client.disconnect(throwable);
                            }
                        }
                    }
                }
            }
        }

    };
    peerThread.start();
    log.debug("Created and started peer update thread");
    log.info("Connected to server with address " + address);
}

From source file:com.whirvis.jraknet.discovery.DiscoveryThread.java

License:Open Source License

/**
 * Allocates a discovery thread./*from   ww w .  java 2 s .  c  o m*/
 */
protected DiscoveryThread() {
    this.log = LogManager.getLogger(DiscoveryThread.class);
    this.bootstrap = new Bootstrap();
    this.group = new NioEventLoopGroup();
    this.handler = new DiscoveryHandler();
    bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
    bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
    try {
        this.channel = bootstrap.bind(0).sync().channel();
    } catch (InterruptedException e) {
        this.interrupt(); // Cause thread to immediately break out of loop
        Discovery.setDiscoveryMode(DiscoveryMode.DISABLED);
        log.error("Failed to bind channel necessary for broadcasting pings, disabled discovery system");
    }
    this.setName(log.getName());
}

From source file:com.whirvis.jraknet.RakNet.java

License:Open Source License

/**
 * Sends a packet to the specified address.
 * /*from  ww w.ja v  a 2  s.  c om*/
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            how long to wait until resending the packet.
 * @param retries
 *            how many times the packet will be sent before giving up.
 * @return the packet received in response, <code>null</code> if no response
 *         was received or the thread was interrupted.
 * @throws NullPointerException
 *             if the <code>address</code>, IP address of the
 *             <code>address</code>, or <code>packet</code> are
 *             <code>null</code>.
 * @throws IllegalArgumentException
 *             if the <code>timeout</code> or <code>retries</code> are less
 *             than or equal to <code>0</code>.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) throws NullPointerException, IllegalArgumentException {
    if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    } else if (packet == null) {
        throw new NullPointerException("Packet cannot be null");
    } else if (timeout <= 0) {
        throw new IllegalArgumentException("Timeout must be greater than 0");
    } else if (retries <= 0) {
        throw new IllegalArgumentException("Retriest must be greater than 0");
    }

    // Prepare bootstrap
    RakNetPacket received = null;
    EventLoopGroup group = new NioEventLoopGroup();
    int maximumTransferUnit = getMaximumTransferUnit();
    if (maximumTransferUnit < MINIMUM_MTU_SIZE) {
        return null;
    }
    try {
        // Create bootstrap
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, maximumTransferUnit)
                .option(ChannelOption.SO_SNDBUF, maximumTransferUnit).handler(handler);
        Channel channel = bootstrap.bind(0).sync().channel();

        // Wait for response
        while (retries > 0 && received == null && !Thread.currentThread().isInterrupted()) {
            long sendTime = System.currentTimeMillis();
            channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));
            while (System.currentTimeMillis() - sendTime < timeout && handler.packet == null)
                ; // Wait for either a timeout or a response
            received = handler.packet;
            retries--;
        }
    } catch (InterruptedException e) {
        return null;
    }
    group.shutdownGracefully();
    return received;
}