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:groovyx.gpars.remote.netty.discovery.DiscoveryClient.java

License:Apache License

public DiscoveryClient(final int broadcastPort) {
    registeredPromises = new ConcurrentHashMap<String, DataflowVariable<InetSocketAddress>>();

    group = new NioEventLoopGroup();

    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
            .handler(new ChannelInitializer<DatagramChannel>() {
                @Override/*from   w w  w. j ava  2s.  c o  m*/
                protected void initChannel(DatagramChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", new DiscoveryResponseDecoder());
                    pipeline.addLast("encoder", new DiscoveryRequestEncoder(broadcastPort));
                    pipeline.addLast("handler", new DiscoveryClientHandler(registeredPromises));
                }
            });

    channelFuture = bootstrap.bind(0);
}

From source file:groovyx.gpars.remote.netty.discovery.DiscoveryServer.java

License:Apache License

public DiscoveryServer(int broadcastPort, final InetSocketAddress serverSocketAddress,
        final RemotingContextWithUrls remotingContext) {
    group = new NioEventLoopGroup();

    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
            .handler(new ChannelInitializer<DatagramChannel>() {
                @Override//from w ww  .j av a  2  s.c  o  m
                protected void initChannel(DatagramChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder", new DiscoveryRequestDecoder());
                    pipeline.addLast("encoder", new DiscoveryResponseWithRecipientEncoder());
                    pipeline.addLast("handler",
                            new DiscoveryServerHandler(serverSocketAddress, remotingContext));
                }
            });

    channelFuture = bootstrap.bind(broadcastPort);
}

From source file:hms.webrtc.udp.proxy.RtpPartyA.java

License:Apache License

public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from w  ww . j av  a2 s  .com
        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();
    }
}

From source file:hms.webrtc.udp.proxy.RtpPartyB.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  w ww  . ja  v a 2  s. co  m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new RtpPartyBHandler());

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

From source file:io.haze.transport.udp.UDPTransportServer.java

License:Apache License

/**
 * Run this {@link UDPTransportServer}.//w  w w.j av a2 s  .  c  om
 */
@Override
public void run() {
    EventLoopGroup eventGroup = new NioEventLoopGroup();

    try {
        Bootstrap bootstrap = new Bootstrap();
        ChannelPipelineInitializer pipelineInitializer = getChannelPipelineInitializer();

        pipelineInitializer.initialize();

        bootstrap.group(eventGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(pipelineInitializer);

        Channel channel = bootstrap.bind(host, port).sync().channel();

        logger.info(String.format("%s running on %s:%d", getClass().getSimpleName(), host, port));

        super.run();

        channel.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        eventGroup.shutdownGracefully();
    }
}

From source file:io.reactivex.netty.client.AbstractClientBuilder.java

License:Apache License

public B defaultUdpOptions() {
    defaultChannelOptions();
    return channelOption(ChannelOption.SO_BROADCAST, true);
}

From source file:io.reactivex.netty.protocol.udp.server.UdpServerBuilder.java

License:Apache License

@Override
public UdpServerBuilder<I, O> defaultChannelOptions() {
    channelOption(ChannelOption.SO_BROADCAST, true);
    return super.defaultChannelOptions();
}

From source file:net.marfgamer.jraknet.client.RakNetClient.java

License:Open Source License

/**
 * Constructs a <code>RakNetClient</code> with the specified
 * <code>DiscoveryMode</code> and server discovery port.
 * /*  www  .j a  v a 2  s  .co m*/
 * @param discoveryMode
 *            how the client will discover servers. If this is set to
 *            <code>null</code>, the client will enable set it to
 *            <code>DiscoveryMode.ALL_CONNECTIONS</code> as long as the port
 *            is greater than -1.
 * @param discoveryPorts
 *            the ports the client will attempt to discover servers on.
 */
public RakNetClient(DiscoveryMode discoveryMode, int... discoveryPorts) {
    // Set client data
    UUID uuid = UUID.randomUUID();
    this.guid = uuid.getMostSignificantBits();
    this.pingId = uuid.getLeastSignificantBits();
    this.timestamp = System.currentTimeMillis();

    // Set discovery data
    this.discoveryPorts = new HashSet<Integer>();
    this.discoveryMode = discoveryMode;
    this.setDiscoveryPorts(discoveryPorts);
    if (discoveryMode == null) {
        this.discoveryMode = (discoveryPorts.length > 0 ? DiscoveryMode.ALL_CONNECTIONS : DiscoveryMode.NONE);
    }
    this.discovered = new ConcurrentHashMap<InetSocketAddress, DiscoveredServer>();
    this.externalServers = new ConcurrentHashMap<InetSocketAddress, DiscoveredServer>();

    // Set networking data
    this.bootstrap = new Bootstrap();
    this.group = new NioEventLoopGroup();
    this.handler = new RakNetClientHandler(this);

    // Add maximum transfer units
    this.maximumTransferUnits = new IntMap<MaximumTransferUnit>();
    MaximumTransferUnit firstTransferUnit = new MaximumTransferUnit(1464, 3);
    if (RakNetUtils.getMaximumTransferUnit() >= firstTransferUnit.getMaximumTransferUnit()) {
        this.addMaximumTransferUnit(new MaximumTransferUnit(RakNetUtils.getMaximumTransferUnit(), 2));
    }
    this.addMaximumTransferUnit(firstTransferUnit);
    this.addMaximumTransferUnit(new MaximumTransferUnit(1172, 4));
    this.addMaximumTransferUnit(new MaximumTransferUnit(RakNet.MINIMUM_TRANSFER_UNIT, 5));

    // Initiate bootstrap data
    try {
        bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
        this.channel = bootstrap.bind(0).sync().channel();
        RakNetLogger.debug(this, "Created and bound bootstrap");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:net.marfgamer.jraknet.server.RakNetServer.java

License:Open Source License

/**
 * Starts the server./* w  w  w. j  a  v  a2s.  c  om*/
 * 
 * @throws NoListenerException
 *             if the listener has not yet been set.
 */
public final void start() throws NoListenerException {
    // Make sure we have an adapter
    if (listener == null) {
        throw new NoListenerException();
    }

    // Create bootstrap and bind the channel
    try {
        bootstrap.channel(NioDatagramChannel.class).group(group).handler(handler);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false);
        this.channel = bootstrap.bind(port).sync().channel();
        this.running = true;
        RakNetLogger.debug(this, "Created and bound bootstrap");
    } catch (InterruptedException e) {
        e.printStackTrace();
        this.running = false;
    }

    // Notify API
    RakNetLogger.info(this, "Started server");
    listener.onServerStart();

    // Update system
    while (this.running == true) {
        if (sessions.size() <= 0) {
            continue; // Do not loop through non-existent sessions
        }
        synchronized (sessions) {
            for (RakNetClientSession session : sessions.values()) {
                try {
                    // Update session and make sure it isn't DOSing us
                    session.update();
                    if (session.getPacketsReceivedThisSecond() >= RakNet.getMaxPacketsPerSecond()) {
                        this.blockAddress(session.getInetAddress(), "Too many packets",
                                RakNet.MAX_PACKETS_PER_SECOND_BLOCK);
                    }
                } catch (Throwable throwable) {
                    // An error related to the session occurred, remove it
                    listener.onSessionException(session, throwable);
                    this.removeSession(session, throwable.getMessage());
                }
            }
        }
    }
}

From source file:net.marfgamer.jraknet.util.RakNetUtils.java

License:Open Source License

/**
 * Sends a raw message to the specified address for the specified amount of
 * times in the specified interval until the packet is received or there is
 * a timeout./* ww  w  .j a va 2s .  c o m*/
 * 
 * @param address
 *            the address to send the packet to.
 * @param packet
 *            the packet to send.
 * @param timeout
 *            the interval of which the packet is sent.
 * @param retries
 *            how many times the packet will be sent.
 * @return the received packet if it was received.
 */
private static RakNetPacket createBootstrapAndSend(InetSocketAddress address, Packet packet, long timeout,
        int retries) {
    RakNetPacket packetReceived = null;

    // Create bootstrap and bind
    EventLoopGroup group = new NioEventLoopGroup();

    try {
        Bootstrap bootstrap = new Bootstrap();
        BootstrapHandler handler = new BootstrapHandler();
        bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .option(ChannelOption.SO_RCVBUF, RakNet.MINIMUM_TRANSFER_UNIT)
                .option(ChannelOption.SO_SNDBUF, RakNet.MINIMUM_TRANSFER_UNIT).handler(handler);

        // Create channel, send packet, and close it
        Channel channel = bootstrap.bind(0).sync().channel();
        channel.writeAndFlush(new DatagramPacket(packet.buffer(), address));

        // Wait for packet to come in, return null on timeout
        while (retries > 0) {
            long sendTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - sendTime < timeout) {
                if (handler.packet != null) {
                    packetReceived = handler.packet;
                    break; // We found the packet
                }
            }
            if (packetReceived != null) {
                break; // the master loop is no longer needed
            }
            retries--;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Shutdown bootstrap
    group.shutdownGracefully();
    return packetReceived;
}