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:net.tomp2p.connection.ChannelCreator.java

License:Apache License

/**
 * Creates a "channel" to the given address. This won't send any message
 * unlike TCP./* w  w w  .j  a  v a  2 s .  co m*/
 * 
 * @param broadcast
 *            Sets this channel to be able to broadcast
 * @param channelHandlers
 *            The handlers to set
 * @param futureResponse
 *            The futureResponse
 * @return The channel future object or null if we are shut down
 */
public ChannelFuture createUDP(final boolean broadcast,
        final Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers,
        FutureResponse futureResponse) {
    readUDP.lock();
    try {
        if (shutdownUDP) {
            return null;
        }
        if (!semaphoreUPD.tryAcquire()) {
            LOG.error("Tried to acquire more resources (UDP) than announced! Announced {}", maxPermitsUDP);
            throw new RuntimeException("Tried to acquire more resources (UDP) than announced!");
        }
        final Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioDatagramChannel.class);
        b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(ConnectionBean.UDP_LIMIT));
        if (broadcast) {
            b.option(ChannelOption.SO_BROADCAST, true);
        }
        Map<String, Pair<EventExecutorGroup, ChannelHandler>> channelHandlers2 = channelClientConfiguration
                .pipelineFilter().filter(channelHandlers, false, true);
        addHandlers(b, channelHandlers2);
        // Here we need to bind, as opposed to the TCP, were we connect if
        // we do a connect, we cannot receive
        // broadcast messages
        final ChannelFuture channelFuture;
        channelFuture = b.bind(new InetSocketAddress(channelClientConfiguration.senderUDP(), 0));
        recipients.add(channelFuture.channel());
        setupCloseListener(channelFuture, semaphoreUPD, futureResponse);
        return channelFuture;
    } finally {
        readUDP.unlock();
    }
}

From source file:net.tomp2p.connection.ChannelServer.java

License:Apache License

/**
 * Start to listen on a UPD port.//from   w  w w  .  j a  v a  2s.  c o  m
 * 
 * @param listenAddresses
 *            The address to listen to
 * @param config
 *            Can create handlers to be attached to this port
 * @param broadcastFlag 
 * @return True if startup was successful
 */
boolean startupUDP(final InetSocketAddress listenAddresses, final ChannelServerConfiguration config,
        boolean broadcastFlag) {
    Bootstrap b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioDatagramChannel.class);
    //option broadcast only required as we not listen to the broadcast address directly
    if (broadcastFlag) {
        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 {
            ch.config().setAllocator(channelServerConfiguration.byteBufAllocator());
            for (Map.Entry<String, Pair<EventExecutorGroup, ChannelHandler>> entry : handlers(false)
                    .entrySet()) {
                if (!entry.getValue().isEmpty()) {
                    ch.pipeline().addLast(entry.getValue().element0(), entry.getKey(),
                            entry.getValue().element1());
                } else if (entry.getValue().element1() != null) {
                    ch.pipeline().addLast(entry.getKey(), entry.getValue().element1());
                }
            }
        }
    });

    ChannelFuture future = b.bind(listenAddresses);
    channelsUDP.put(listenAddresses.getAddress(), future.channel());
    return handleFuture(future);
}

From source file:net.tomp2p.connection2.ChannelCreator.java

License:Apache License

/**
 * Creates a "channel" to the given address. This won't send any message unlike TCP.
 * /*from   w  w  w.  j  a v a  2s.  com*/
 * @param recipient
 *            The recipient of the a message
 * 
 * @param broadcast
 *            Sets this channel to be able to broadcast
 * @param channelHandlers
 *            The handlers to set
 * @return The channel future object or null if we are shut down
 */
public ChannelFuture createUDP(final SocketAddress recipient, final boolean broadcast,
        final Map<String, ChannelHandler> channelHandlers) {
    readUDP.lock();
    try {
        if (shutdownUDP) {
            return null;
        }
        if (!semaphoreUPD.tryAcquire()) {
            LOG.error("Tried to acquire more resources (UDP) than announced!");
            throw new RuntimeException("Tried to acquire more resources (UDP) than announced!");
        }
        final Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioDatagramChannel.class);
        b.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(ConnectionBean.UDP_LIMIT));
        if (broadcast) {
            b.option(ChannelOption.SO_BROADCAST, true);
        }
        channelClientConfiguration.pipelineFilter().filter(channelHandlers, false, true);
        addHandlers(b, channelHandlers);
        // Here we need to bind, as opposed to the TCP, were we connect if we do a connect, we cannot receive
        // broadcast messages
        final ChannelFuture channelFuture;
        if (broadcast) {
            channelFuture = b.bind(new InetSocketAddress(0));
        } else {
            channelFuture = b.connect(recipient);
        }

        setupCloseListener(channelFuture, semaphoreUPD);
        CREATED_UDP_CONNECTIONS.incrementAndGet();
        return channelFuture;
    } finally {
        readUDP.unlock();
    }
}

From source file:net.tomp2p.connection2.ChannelServer.java

License:Apache License

/**
 * Start to listen on a UPD port./*from  w  w w .j  a  v a 2  s  .co m*/
 * 
 * @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);
}

From source file:nz.co.fortytwo.signalk.server.NettyServer.java

License:Open Source License

public void run() throws Exception {
    forwardingHandler = new CamelNettyHandler(outputType);
    // The generic TCP socket server
    ServerBootstrap skBootstrap = new ServerBootstrap();
    skBootstrap.group(group, workerGroup).channel(NioServerSocketChannel.class).localAddress(tcpPort)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w w w  .j  a v  a2s  .com*/
                public void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                    pipeline.addLast(DECODER);
                    pipeline.addLast(ENCODER);
                    pipeline.addLast(forwardingHandler);
                    logger.info("Signal K " + outputType + " Connection over TCP from:"
                            + socketChannel.remoteAddress());

                }

            });
    final ChannelFuture signalkTcpFuture = skBootstrap.bind().sync();
    logger.info("Server listening on TCP " + signalkTcpFuture.channel().localAddress());
    signalkTcpFuture.channel().closeFuture();

    if (udpPort > 0) {
        udpHandler = new CamelUdpNettyHandler(outputType);

        Bootstrap udpBootstrap = new Bootstrap();
        udpBootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(udpHandler);
        udpChannel = udpBootstrap.bind(tcpPort - 1).sync().channel();
        logger.info("Server listening on UDP " + udpChannel.localAddress());
    }
}

From source file:org.apache.camel.component.netty4.NettyProducer.java

License:Apache License

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;/*from w ww.j ava2  s .  c om*/

    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        Bootstrap clientBootstrap = new Bootstrap();
        clientBootstrap.channel(NioSocketChannel.class);
        clientBootstrap.group(getWorkerGroup());
        clientBootstrap.option(ChannelOption.SO_KEEPALIVE, configuration.isKeepAlive());
        clientBootstrap.option(ChannelOption.TCP_NODELAY, configuration.isTcpNoDelay());
        clientBootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
        clientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            clientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.handler(pipelineFactory);
        answer = clientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}",
                    new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        Bootstrap connectionlessClientBootstrap = new Bootstrap();
        connectionlessClientBootstrap.channel(NioDatagramChannel.class);
        connectionlessClientBootstrap.group(getWorkerGroup());
        connectionlessClientBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
                configuration.getConnectTimeout());
        connectionlessClientBootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
        connectionlessClientBootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
        connectionlessClientBootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());

        //TODO need to check it later
        // set any additional netty options
        /*
        if (configuration.getOptions() != null) {
        for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
            connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
        }
        }*/

        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.handler(pipelineFactory);
        // bind and store channel so we can close it when stopping
        ChannelFuture channelFuture = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
        channelFuture.awaitUninterruptibly();
        Channel channel = channelFuture.channel();
        allChannels.add(channel);
        answer = connectionlessClientBootstrap
                .connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] {
                    configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap });
        }
        return answer;
    }
}

From source file:org.apache.camel.component.netty4.SingleUDPNettyServerBootstrapFactory.java

License:Apache License

protected void startServerBootstrap() throws Exception {
    // create non-shared worker pool
    EventLoopGroup wg = configuration.getWorkerGroup();
    if (wg == null) {
        // create new pool which we should shutdown when stopping as its not shared
        workerGroup = new NettyWorkerPoolBuilder().withWorkerCount(configuration.getWorkerCount())
                .withName("NettyServerTCPWorker").build();
        wg = workerGroup;// w  ww. j a  v  a  2 s . com
    }

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(wg).channel(NioDatagramChannel.class);
    // We cannot set the child option here      
    bootstrap.option(ChannelOption.SO_REUSEADDR, configuration.isReuseAddress());
    bootstrap.option(ChannelOption.SO_SNDBUF, configuration.getSendBufferSize());
    bootstrap.option(ChannelOption.SO_RCVBUF, configuration.getReceiveBufferSize());
    bootstrap.option(ChannelOption.SO_BROADCAST, configuration.isBroadcast());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.getConnectTimeout());

    // TODO need to find the right setting of below option
    // only set this if user has specified
    /*
    if (configuration.getReceiveBufferSizePredictor() > 0) {
    bootstrap.setOption("receiveBufferSizePredictorFactory",
            new FixedReceiveBufferSizePredictorFactory(configuration.getReceiveBufferSizePredictor()));
    }*/

    if (configuration.getBacklog() > 0) {
        bootstrap.option(ChannelOption.SO_BACKLOG, configuration.getBacklog());
    }

    //TODO need to check the additional netty options
    /*
    if (configuration.getOptions() != null) {
    for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
        connectionlessBootstrap.setOption(entry.getKey(), entry.getValue());
    }
    }*/

    LOG.debug("Created ConnectionlessBootstrap {}", bootstrap);

    // set the pipeline factory, which creates the pipeline for each newly created channels
    bootstrap.handler(pipelineFactory);

    InetSocketAddress hostAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    SubnetUtils multicastSubnet = new SubnetUtils(MULTICAST_SUBNET);

    if (multicastSubnet.getInfo().isInRange(configuration.getHost())) {
        ChannelFuture channelFuture = bootstrap.bind(hostAddress);
        channelFuture.awaitUninterruptibly();
        channel = channelFuture.channel();
        DatagramChannel datagramChannel = (DatagramChannel) channel;
        String networkInterface = configuration.getNetworkInterface() == null ? LOOPBACK_INTERFACE
                : configuration.getNetworkInterface();
        multicastNetworkInterface = NetworkInterface.getByName(networkInterface);
        ObjectHelper.notNull(multicastNetworkInterface,
                "No network interface found for '" + networkInterface + "'.");
        LOG.info("ConnectionlessBootstrap joining {}:{} using network interface: {}", new Object[] {
                configuration.getHost(), configuration.getPort(), multicastNetworkInterface.getName() });
        datagramChannel.joinGroup(hostAddress, multicastNetworkInterface).syncUninterruptibly();
        allChannels.add(datagramChannel);
    } else {
        LOG.info("ConnectionlessBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture channelFuture = bootstrap.bind(hostAddress);
        channelFuture.awaitUninterruptibly();
        channel = channelFuture.channel();
        allChannels.add(channel);
    }
}

From source file:org.apache.directory.server.dhcp.netty.DhcpServer.java

@PostConstruct
public void start() throws IOException, InterruptedException {
    super.start();

    ThreadFactory factory = new DefaultThreadFactory("dhcp-server");
    EventLoopGroup group = new NioEventLoopGroup(0, factory);

    Bootstrap b = new Bootstrap();
    b.group(group);//from ww w  . j  a v  a  2 s .c  o m
    b.channel(NioDatagramChannel.class);
    b.option(ChannelOption.SO_BROADCAST, true);
    b.handler(new DhcpHandler(service, this));
    channel = b.bind(port).sync().channel();
}

From source file:org.apache.kerby.kerberos.kdc.impl.NettyKdcNetwork.java

License:Apache License

private void startUDPServer() {
    this.group = new NioEventLoopGroup();
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
            .handler((ChannelHandler) new NettyKdcUdpServerHandler(kdcContext));
    b.bind(udpAddress.getPort());/*  w w  w  . ja  v  a 2s  . c  o  m*/
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

License:Open Source License

public static void broadcastVideo(String videoFilePath, String ip, int port, long tsDurationMillis,
        int minDatagramSize, int maxDatagramSize, boolean fractionalTs, String networkInterfaceName) {

    Optional<InetAddress> inetAddressOptional = findLocalAddress(networkInterfaceName);

    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {//from   www .  jav  a 2 s  .  c o  m
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                            DatagramPacket datagramPacket) throws Exception {
                        LOGGER.trace("Reading datagram from channel");
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        LOGGER.error("Exception occurred while handling datagram packet.", cause);
                        ctx.close();
                    }
                });

        Channel ch;

        if (inetAddressOptional.isPresent()) {
            ch = bootstrap.bind(inetAddressOptional.get(), 0).sync().channel();
        } else {
            ch = bootstrap.bind(0).sync().channel();
        }

        File videoFile = new File(videoFilePath);

        long bytesSent = 0;

        long tsPacketCount = videoFile.length() / PACKET_SIZE;

        double delayPerPacket = tsDurationMillis / (double) tsPacketCount;

        long startTime = System.currentTimeMillis();

        Random rand = new Random(0);

        long nextPacketLog = PACKET_LOG_PERIOD;

        long nextByteLog = BYTE_LOG_PERIOD;

        try (final InputStream fis = new BufferedInputStream(new FileInputStream(videoFile))) {
            byte[] buffer = new byte[DISK_IO_BUFFER_SIZE];

            int datagramSize = getPacketSize(rand, minDatagramSize, maxDatagramSize, fractionalTs);

            byte[] dgramBuffer = new byte[datagramSize];

            int writeStart = 0;
            int writeEnd = datagramSize;

            int readEnd;
            while ((readEnd = fis.read(buffer)) != -1) {

                int readStart = 0;

                while (readStart < readEnd) {
                    int bytesToCopy = Math.min(writeEnd - writeStart, readEnd - readStart);
                    System.arraycopy(buffer, readStart, dgramBuffer, writeStart, bytesToCopy);
                    readStart += bytesToCopy;
                    writeStart += bytesToCopy;

                    if (writeStart == writeEnd) {
                        transmit(ch, dgramBuffer, ip, port);
                        bytesSent += dgramBuffer.length;

                        long packetsSent = bytesSent / PACKET_SIZE;

                        long currentTime = System.currentTimeMillis();

                        long elapsedTime = currentTime - startTime;

                        double predictedTime = packetsSent * delayPerPacket;

                        if ((predictedTime - elapsedTime) >= 50) {
                            Thread.sleep((long) predictedTime - elapsedTime);
                        }

                        if (packetsSent >= nextPacketLog) {
                            LOGGER.debug("Packets sent: {}, Bytes sent: {}", packetsSent, bytesSent);
                            nextPacketLog += PACKET_LOG_PERIOD;
                        }

                        if (bytesSent >= nextByteLog) {
                            LOGGER.debug("Packets sent: {}, Bytes sent: {}", packetsSent, bytesSent);
                            nextByteLog += BYTE_LOG_PERIOD;
                        }

                        datagramSize = getPacketSize(rand, minDatagramSize, maxDatagramSize, fractionalTs);

                        dgramBuffer = new byte[datagramSize];
                        writeStart = 0;
                        writeEnd = datagramSize;
                    }

                }

            }

            if (writeStart > 0) {
                byte[] tmp = new byte[writeStart];
                System.arraycopy(dgramBuffer, 0, tmp, 0, tmp.length);
                transmit(ch, tmp, ip, port);
            }

        }

        long endTime = System.currentTimeMillis();

        LOGGER.trace("Time Elapsed: {}", endTime - startTime);
        LOGGER.trace("Elapsed Time minus predicted time: {}", (endTime - startTime) - tsDurationMillis);

        if (!ch.closeFuture().await(100)) {
            LOGGER.error("Channel timeout");
        }

        LOGGER.trace("Bytes sent: {} ", bytesSent);
    } catch (InterruptedException | IOException e) {
        LOGGER.error("Unable to generate stream.", e);
    } finally {
        // Shut down the event loop to terminate all threads.
        eventLoopGroup.shutdownGracefully();
    }
}