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.whirvis.jraknet.server.RakNetServer.java

License:Open Source License

/**
 * Starts the server./*  ww  w .j a  v  a2s.  c  o m*/
 * 
 * @throws IllegalStateException
 *             if the server is already running.
 * @throws RakNetException
 *             if an error occurs during startup.
 */
public void start() throws IllegalStateException, RakNetException {
    if (running == true) {
        throw new IllegalStateException("Server is already running");
    } else if (listeners.isEmpty()) {
        log.warn("Server has no listeners");
    }

    try {
        this.bootstrap = new Bootstrap();
        this.group = new NioEventLoopGroup();
        this.handler = new RakNetServerHandler(this);
        bootstrap.handler(handler);

        // Create bootstrap and bind channel
        bootstrap.channel(NioDatagramChannel.class).group(group);
        bootstrap.option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, false)
                .option(ChannelOption.SO_SNDBUF, maximumTransferUnit)
                .option(ChannelOption.SO_RCVBUF, maximumTransferUnit);
        this.channel = (bindingAddress != null ? bootstrap.bind(bindingAddress) : bootstrap.bind(0)).sync()
                .channel();
        this.bindAddress = (InetSocketAddress) channel.localAddress();
        this.running = true;
        log.debug("Created and bound bootstrap");

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

            @Override
            public void run() {
                HashMap<RakNetClientPeer, Throwable> disconnected = new HashMap<RakNetClientPeer, Throwable>();
                while (server.running == true && !this.isInterrupted()) {
                    try {
                        Thread.sleep(0, 1); // Lower CPU usage
                    } catch (InterruptedException e) {
                        this.interrupt(); // Interrupted during sleep
                        continue;
                    }
                    for (RakNetClientPeer peer : clients.values()) {
                        if (!peer.isDisconnected()) {
                            try {
                                peer.update();
                                if (peer.getPacketsReceivedThisSecond() >= RakNet.getMaxPacketsPerSecond()) {
                                    server.blockAddress(peer.getInetAddress(), "Too many packets",
                                            RakNet.MAX_PACKETS_PER_SECOND_BLOCK);
                                }
                            } catch (Throwable throwable) {
                                server.callEvent(listener -> listener.onPeerException(server, peer, throwable));
                                disconnected.put(peer, throwable);
                            }
                        }
                    }

                    /*
                     * Disconnect peers.
                     * 
                     * This must be done here as simply removing a client
                     * from the clients map would be an incorrect way of
                     * disconnecting a client. This means that calling the
                     * disconnect() method is required. However, calling it
                     * while in the loop would cause a
                     * ConcurrentModifactionException. To get around this,
                     * the clients that need to be disconnected are properly
                     * disconnected after the loop is finished. This is done
                     * simply by having them and their disconnect reason be
                     * put in a disconnection map.
                     */
                    if (disconnected.size() > 0) {
                        for (RakNetClientPeer peer : disconnected.keySet()) {
                            server.disconnect(peer, disconnected.get(peer));
                        }
                        disconnected.clear();
                    }
                }
            }

        };
        peerThread.start();
        log.debug("Created and started peer update thread");
        this.callEvent(listener -> listener.onStart(this));
    } catch (InterruptedException e) {
        this.running = false;
        throw new RakNetException(e);
    }
    log.info("Started server");
}

From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java

License:Open Source License

/**
 * Constructor.//from   w  w w.  j  a v  a2 s.c om
 *
 * @param listener the listener to invoke when cameras are discovered
 * @param searchRequestFrequencySeconds the frequency at which to send out discovery requests
 */
public FoscamCameraDiscovery(CameraDiscoveryListener listener, int searchRequestFrequencySeconds) {
    this.listener = listener;
    this.getSearchRequestFrequencySeconds = searchRequestFrequencySeconds;

    group = new NioEventLoopGroup(1);
    bootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class)
            .option(ChannelOption.SO_BROADCAST, true);
}

From source file:com.zhaopeng.timeserver.protocol.udp.ChineseProverbServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/*from  w w  w  .  j  a va  2 s .c  om*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbServerHandler());

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

From source file:de.unipassau.isl.evs.ssh.core.network.UDPDiscoveryClient.java

License:Open Source License

/**
 * Start discovery if it is not running yet and send the first discovery request.
 *///from   w  w w . ja  v  a 2 s  .  c o  m
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();
    }
}

From source file:de.unipassau.isl.evs.ssh.master.network.UDPDiscoveryServer.java

License:Open Source License

@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();/*from   w  w w  . j  a  va2  s  .  c  om*/

    // 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);
}

From source file:dorkbox.network.Broadcast.java

License:Apache License

static List<BroadcastResponse> discoverHosts0(Logger logger, int udpPort, int discoverTimeoutMillis,
        boolean fetchAllServers) throws IOException {
    // fetch a buffer that contains the serialized object.
    ByteBuf buffer = Unpooled.buffer(1);
    buffer.writeByte(MagicBytes.broadcastID);

    List<BroadcastResponse> servers = new ArrayList<BroadcastResponse>();

    Enumeration<NetworkInterface> networkInterfaces;
    try {// w  w  w . ja v a2  s. c o  m
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        if (logger != null) {
            logger.error("Host discovery failed.", e);
        }
        throw new IOException("Host discovery failed. No interfaces found.");
    }

    scan: for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress address = interfaceAddress.getAddress();
            InetAddress broadcast = interfaceAddress.getBroadcast();

            // don't use IPv6!
            if (address instanceof Inet6Address) {
                if (logger != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Not using IPv6 address: {}", address);
                    }
                }
                continue;
            }

            try {
                if (logger != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Searching for host on [{}:{}]", address.getHostAddress(), udpPort);
                    }
                }

                EventLoopGroup group;
                Class<? extends Channel> channelClass;

                if (OS.isAndroid()) {
                    // android ONLY supports OIO (not NIO)
                    group = new OioEventLoopGroup(1);
                    channelClass = OioDatagramChannel.class;
                } else {
                    group = new NioEventLoopGroup(1);
                    channelClass = NioDatagramChannel.class;
                }

                Bootstrap udpBootstrap = new Bootstrap().group(group).channel(channelClass)
                        .option(ChannelOption.SO_BROADCAST, true).handler(new ClientDiscoverHostInitializer())
                        .localAddress(new InetSocketAddress(address, 0)); // pick random address. Not listen for broadcast.

                // we don't care about RECEIVING a broadcast packet, we are only SENDING one.
                ChannelFuture future;
                try {
                    future = udpBootstrap.bind();
                    future.await();
                } catch (InterruptedException e) {
                    if (logger != null) {
                        logger.error("Could not bind to random UDP address on the server.", e.getCause());
                    }
                    throw new IOException("Could not bind to random UDP address on the server.");
                }

                if (!future.isSuccess()) {
                    if (logger != null) {
                        logger.error("Could not bind to random UDP address on the server.", future.cause());
                    }
                    throw new IOException("Could not bind to random UDP address on the server.");
                }

                Channel channel1 = future.channel();

                if (broadcast != null) {
                    // try the "defined" broadcast first if we have it (not always!)
                    channel1.writeAndFlush(
                            new DatagramPacket(buffer, new InetSocketAddress(broadcast, udpPort)));

                    // response is received.  If the channel is not closed within 5 seconds, move to the next one.
                    if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) {
                        if (logger != null) {
                            if (logger.isInfoEnabled()) {
                                logger.info("Host discovery timed out.");
                            }
                        }
                    } else {
                        BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE)
                                .get();
                        servers.add(broadcastResponse);
                    }

                    // keep going if we want to fetch all servers. Break if we found one.
                    if (!(fetchAllServers || servers.isEmpty())) {
                        channel1.close().await();
                        group.shutdownGracefully().await();
                        break scan;
                    }
                }

                // continue with "common" broadcast addresses.
                // Java 1.5 doesn't support getting the subnet mask, so try them until we find one.

                byte[] ip = address.getAddress();
                for (int octect = 3; octect >= 0; octect--) {
                    ip[octect] = -1; // 255.255.255.0

                    // don't error out on one particular octect
                    try {
                        InetAddress byAddress = InetAddress.getByAddress(ip);
                        channel1.writeAndFlush(
                                new DatagramPacket(buffer, new InetSocketAddress(byAddress, udpPort)));

                        // response is received.  If the channel is not closed within 5 seconds, move to the next one.
                        if (!channel1.closeFuture().awaitUninterruptibly(discoverTimeoutMillis)) {
                            if (logger != null) {
                                if (logger.isInfoEnabled()) {
                                    logger.info("Host discovery timed out.");
                                }
                            }
                        } else {
                            BroadcastResponse broadcastResponse = channel1.attr(ClientDiscoverHostHandler.STATE)
                                    .get();
                            servers.add(broadcastResponse);

                            if (!fetchAllServers) {
                                break;
                            }
                        }
                    } catch (Exception ignored) {
                    }
                }

                channel1.close().sync();
                group.shutdownGracefully(0, discoverTimeoutMillis, TimeUnit.MILLISECONDS);

            } catch (Exception ignored) {
            }

            // keep going if we want to fetch all servers. Break if we found one.
            if (!(fetchAllServers || servers.isEmpty())) {
                break scan;
            }
        }
    }

    if (logger != null && logger.isInfoEnabled() && !servers.isEmpty()) {
        StringBuilder stringBuilder = new StringBuilder(256);

        if (fetchAllServers) {
            stringBuilder.append("Discovered servers: (").append(servers.size()).append(")");

            for (BroadcastResponse server : servers) {
                stringBuilder.append("/n").append(server.remoteAddress).append(":");

                if (server.tcpPort > 0) {
                    stringBuilder.append(server.tcpPort);

                    if (server.udpPort > 0) {
                        stringBuilder.append(":");
                    }
                }
                if (server.udpPort > 0) {
                    stringBuilder.append(udpPort);
                }
            }
            logger.info(stringBuilder.toString());
        } else {
            BroadcastResponse server = servers.get(0);
            stringBuilder.append(server.remoteAddress).append(":");

            if (server.tcpPort > 0) {
                stringBuilder.append(server.tcpPort);

                if (server.udpPort > 0) {
                    stringBuilder.append(":");
                }
            }
            if (server.udpPort > 0) {
                stringBuilder.append(udpPort);
            }

            logger.info("Discovered server [{}]", stringBuilder.toString());
        }
    }

    return servers;
}

From source file:dorkbox.network.Client.java

License:Apache License

/**
 * Starts a REMOTE <b>only</b> client, which will connect to the specified host using the specified Connections Options
 *///  w w w  .  j  a  va2  s.  c o  m
@SuppressWarnings("AutoBoxing")
public Client(final Configuration config) throws SecurityException {
    super(config);

    String threadName = Client.class.getSimpleName();

    this.config = config;
    boolean hostConfigured = (config.tcpPort > 0 || config.udpPort > 0) && config.host != null;
    boolean isLocalChannel = config.localChannelName != null;

    if (isLocalChannel && hostConfigured) {
        String msg = threadName
                + " Local channel use and TCP/UDP use are MUTUALLY exclusive. Unable to determine what to do.";
        logger.error(msg);
        throw new IllegalArgumentException(msg);
    }

    localChannelName = config.localChannelName;
    hostName = config.host;

    Bootstrap localBootstrap = null;
    Bootstrap tcpBootstrap = null;
    Bootstrap udpBootstrap = null;

    if (config.localChannelName != null) {
        localBootstrap = new Bootstrap();
    }

    if (config.tcpPort > 0 || config.udpPort > 0) {
        if (config.host == null) {
            throw new IllegalArgumentException("You must define what host you want to connect to.");
        }

        if (config.host.equals("0.0.0.0")) {
            throw new IllegalArgumentException(
                    "You cannot connect to 0.0.0.0, you must define what host you want to connect to.");
        }
    }

    if (config.tcpPort > 0) {
        tcpBootstrap = new Bootstrap();
    }

    if (config.udpPort > 0) {
        udpBootstrap = new Bootstrap();
    }

    if (localBootstrap == null && tcpBootstrap == null && udpBootstrap == null) {
        throw new IllegalArgumentException(
                "You must define how you want to connect, either LOCAL channel name, TCP port, or UDP port");
    }

    if (config.localChannelName != null) {
        // no networked bootstraps. LOCAL connection only

        bootstraps.add(new BootstrapWrapper("LOCAL", config.localChannelName, -1, localBootstrap));

        localBootstrap.group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS")).channel(LocalChannel.class)
                .remoteAddress(new LocalAddress(config.localChannelName))
                .handler(new RegistrationLocalHandlerClient(threadName, registrationWrapper));
    }

    EventLoopGroup workerEventLoop = null;
    if (tcpBootstrap != null || udpBootstrap != null) {
        workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName);
    }

    if (tcpBootstrap != null) {
        bootstraps.add(new BootstrapWrapper("TCP", config.host, config.tcpPort, tcpBootstrap));

        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            tcpBootstrap.channel(OioSocketChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            tcpBootstrap.channel(EpollSocketChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            tcpBootstrap.channel(KQueueSocketChannel.class);
        } else {
            tcpBootstrap.channel(NioSocketChannel.class);
        }

        tcpBootstrap.group(newEventLoop(1, threadName + "-TCP-BOSS"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .remoteAddress(config.host, config.tcpPort).handler(new RegistrationRemoteHandlerClientTCP(
                        threadName, registrationWrapper, workerEventLoop));

        // android screws up on this!!
        tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).option(ChannelOption.SO_KEEPALIVE,
                true);
    }

    if (udpBootstrap != null) {
        bootstraps.add(new BootstrapWrapper("UDP", config.host, config.udpPort, udpBootstrap));

        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            udpBootstrap.channel(OioDatagramChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            udpBootstrap.channel(EpollDatagramChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            udpBootstrap.channel(KQueueDatagramChannel.class);
        } else {
            udpBootstrap.channel(NioDatagramChannel.class);
        }

        udpBootstrap.group(newEventLoop(1, threadName + "-UDP-BOSS"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                // Netty4 has a default of 2048 bytes as upper limit for datagram packets.
                .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(EndPoint.udpMaxSize))
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .localAddress(new InetSocketAddress(0)) // bind to wildcard
                .remoteAddress(new InetSocketAddress(config.host, config.udpPort))
                .handler(new RegistrationRemoteHandlerClientUDP(threadName, registrationWrapper,
                        workerEventLoop));

        // Enable to READ and WRITE MULTICAST data (ie, 192.168.1.0)
        // in order to WRITE: write as normal, just make sure it ends in .255
        // in order to LISTEN:
        //    InetAddress group = InetAddress.getByName("203.0.113.0");
        //    NioDatagramChannel.joinGroup(group);
        // THEN once done
        //    NioDatagramChannel.leaveGroup(group), close the socket
        udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize);
    }
}

From source file:dorkbox.network.Server.java

License:Apache License

/**
 * Convenience method to starts a server with the specified Connection Options
 *//*from w  w  w . j a  va 2s . c  om*/
@SuppressWarnings("AutoBoxing")
public Server(Configuration config) throws SecurityException {
    // watch-out for serialization... it can be NULL incoming. The EndPoint (superclass) sets it, if null, so
    // you have to make sure to use this.serialization
    super(config);

    tcpPort = config.tcpPort;
    udpPort = config.udpPort;

    localChannelName = config.localChannelName;

    if (config.host == null) {
        // we set this to "0.0.0.0" so that it is clear that we are trying to bind to that address.
        hostName = "0.0.0.0";

        // make it clear that this is what we do (configuration wise) so that variable examination is consistent
        config.host = hostName;
    } else {
        hostName = config.host;
    }

    if (localChannelName != null) {
        localBootstrap = new ServerBootstrap();
    } else {
        localBootstrap = null;
    }

    if (tcpPort > 0) {
        tcpBootstrap = new ServerBootstrap();
    } else {
        tcpBootstrap = null;
    }

    if (udpPort > 0) {
        // This is what allows us to have UDP behave "similar" to TCP, in that a session is established based on the port/ip of the
        // remote connection. This allows us to reuse channels and have "state" for a UDP connection that normally wouldn't exist.
        // Additionally, this is what responds to discovery broadcast packets
        udpBootstrap = new SessionBootstrap(tcpPort, udpPort);
    } else {
        udpBootstrap = null;
    }

    String threadName = Server.class.getSimpleName();

    // always use local channels on the server.
    if (localBootstrap != null) {
        localBootstrap
                .group(newEventLoop(LOCAL, 1, threadName + "-JVM-BOSS"), newEventLoop(LOCAL, 1, threadName))
                .channel(LocalServerChannel.class)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))
                .localAddress(new LocalAddress(localChannelName))
                .childHandler(new RegistrationLocalHandlerServer(threadName, registrationWrapper));
    }

    EventLoopGroup workerEventLoop = null;
    if (tcpBootstrap != null || udpBootstrap != null) {
        workerEventLoop = newEventLoop(config.workerThreadPoolSize, threadName);
    }

    if (tcpBootstrap != null) {
        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            tcpBootstrap.channel(OioServerSocketChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            tcpBootstrap.channel(EpollServerSocketChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            tcpBootstrap.channel(KQueueServerSocketChannel.class);
        } else {
            tcpBootstrap.channel(NioServerSocketChannel.class);
        }

        // TODO: If we use netty for an HTTP server,
        // Beside the usual ChannelOptions the Native Transport allows to enable TCP_CORK which may come in handy if you implement a HTTP Server.

        tcpBootstrap
                .group(newEventLoop(1, threadName + "-TCP-BOSS"),
                        newEventLoop(1, threadName + "-TCP-REGISTRATION"))
                .option(ChannelOption.SO_BACKLOG, backlogConnectionCount)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))

                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new RegistrationRemoteHandlerServerTCP(threadName, registrationWrapper,
                        workerEventLoop));

        // have to check options.host for "0.0.0.0". we don't bind to "0.0.0.0", we bind to "null" to get the "any" address!
        if (hostName.equals("0.0.0.0")) {
            tcpBootstrap.localAddress(tcpPort);
        } else {
            tcpBootstrap.localAddress(hostName, tcpPort);
        }

        // android screws up on this!!
        tcpBootstrap.option(ChannelOption.TCP_NODELAY, !OS.isAndroid()).childOption(ChannelOption.TCP_NODELAY,
                !OS.isAndroid());
    }

    if (udpBootstrap != null) {
        if (OS.isAndroid()) {
            // android ONLY supports OIO (not NIO)
            udpBootstrap.channel(OioDatagramChannel.class);
        } else if (OS.isLinux() && NativeLibrary.isAvailable()) {
            // epoll network stack is MUCH faster (but only on linux)
            udpBootstrap.channel(EpollDatagramChannel.class);
        } else if (OS.isMacOsX() && NativeLibrary.isAvailable()) {
            // KQueue network stack is MUCH faster (but only on macosx)
            udpBootstrap.channel(KQueueDatagramChannel.class);
        } else {
            // windows and linux/mac that are incompatible with the native implementations
            udpBootstrap.channel(NioDatagramChannel.class);
        }

        // Netty4 has a default of 2048 bytes as upper limit for datagram packets, we want this to be whatever we specify
        FixedRecvByteBufAllocator recvByteBufAllocator = new FixedRecvByteBufAllocator(EndPoint.udpMaxSize);

        udpBootstrap
                .group(newEventLoop(1, threadName + "-UDP-BOSS"),
                        newEventLoop(1, threadName + "-UDP-REGISTRATION"))
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.RCVBUF_ALLOCATOR, recvByteBufAllocator)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,
                        new WriteBufferWaterMark(WRITE_BUFF_LOW, WRITE_BUFF_HIGH))

                // a non-root user can't receive a broadcast packet on *nix if the socket is bound on non-wildcard address.
                // TODO: move broadcast to it's own handler, and have UDP server be able to be bound to a specific IP
                // OF NOTE: At the end in my case I decided to bind to .255 broadcast address on Linux systems. (to receive broadcast packets)
                .localAddress(udpPort) // if you bind to a specific interface, Linux will be unable to receive broadcast packets! see: http://developerweb.net/viewtopic.php?id=5722
                .childHandler(new RegistrationRemoteHandlerServerUDP(threadName, registrationWrapper,
                        workerEventLoop));

        // // have to check options.host for null. we don't bind to 0.0.0.0, we bind to "null" to get the "any" address!
        // if (hostName.equals("0.0.0.0")) {
        //     udpBootstrap.localAddress(hostName, tcpPort);
        // }
        // else {
        //     udpBootstrap.localAddress(udpPort);
        // }

        // Enable to READ from MULTICAST data (ie, 192.168.1.0)
        // in order to WRITE: write as normal, just make sure it ends in .255
        // in order to LISTEN:
        //    InetAddress group = InetAddress.getByName("203.0.113.0");
        //    socket.joinGroup(group);
        // THEN once done
        //    socket.leaveGroup(group), close the socket
        // Enable to WRITE to MULTICAST data (ie, 192.168.1.0)
        udpBootstrap.option(ChannelOption.SO_BROADCAST, false).option(ChannelOption.SO_SNDBUF, udpMaxSize);
    }
}

From source file:eu.heronnet.module.kad.net.ClientImpl.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    tcpBoostrap = new Bootstrap();
    udpBoostrap = new Bootstrap();
    workerGroup = new NioEventLoopGroup();

    tcpBoostrap.group(workerGroup).channel(NioSocketChannel.class)
            .handler(new HeronResponseChannelInitializer());

    udpBoostrap.group(workerGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
            .handler(udpChannelInitializer);
}

From source file:eu.heronnet.module.kad.net.ServerImpl.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    logger.debug("calling startUp for ServerImpl instance={}", this);

    tcpBoostrap = new ServerBootstrap();
    udpbootrap = new Bootstrap();
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    tcpBoostrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).localAddress(6565)
            .childHandler(tcpChannelInitializer).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);
    tcpBoostrap.bind().sync();//  w  ww . ja v  a  2 s.co  m

    udpbootrap.group(workerGroup).channel(NioDatagramChannel.class).localAddress(6565)
            .handler(udpChannelInitializer).option(ChannelOption.SO_BROADCAST, true);
    udpbootrap.bind().sync();

}