Example usage for java.net StandardSocketOptions SO_BROADCAST

List of usage examples for java.net StandardSocketOptions SO_BROADCAST

Introduction

In this page you can find the example usage for java.net StandardSocketOptions SO_BROADCAST.

Prototype

SocketOption SO_BROADCAST

To view the source code for java.net StandardSocketOptions SO_BROADCAST.

Click Source Link

Document

Allow transmission of broadcast datagrams.

Usage

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

protected void doScan() {

    try {//from w w  w  . ja va  2  s.  c om

        if (!isScanning) {
            isScanning = true;
            if (selector != null) {
                selector.close();
            }

            if (broadcastChannel != null) {
                broadcastChannel.close();
            }

            selector = Selector.open();

            broadcastChannel = DatagramChannel.open(StandardProtocolFamily.INET)
                    .setOption(StandardSocketOptions.SO_REUSEADDR, true)
                    .setOption(StandardSocketOptions.SO_BROADCAST, true);
            broadcastChannel.configureBlocking(false);
            broadcastChannel.socket().setSoTimeout(BROADCAST_TIMEOUT);
            broadcastChannel.bind(new InetSocketAddress(BROADCAST_PORT));

            SelectionKey broadcastKey = broadcastChannel.register(selector,
                    SelectionKey.OP_READ | SelectionKey.OP_WRITE);

            networkJob = scheduler.schedule(networkRunnable, 0, TimeUnit.MILLISECONDS);

            source = UUID.randomUUID().getLeastSignificantBits() & (-1L >>> 32);
            logger.debug("The LIFX discovery service will use '{}' as source identifier",
                    Long.toString(source, 16));

            GetServiceRequest packet = new GetServiceRequest();
            packet.setSequence(SERVICE_REQUEST_SEQ_NO);
            packet.setSource(source);

            broadcastPacket(packet, broadcastKey);
        } else {
            logger.info("A discovery scan for LIFX light is already underway");
        }

    } catch (Exception e) {
        logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
    }

}