Example usage for io.netty.channel.socket InternetProtocolFamily IPv4

List of usage examples for io.netty.channel.socket InternetProtocolFamily IPv4

Introduction

In this page you can find the example usage for io.netty.channel.socket InternetProtocolFamily IPv4.

Prototype

InternetProtocolFamily IPv4

To view the source code for io.netty.channel.socket InternetProtocolFamily IPv4.

Click Source Link

Usage

From source file:com.whizzosoftware.hobson.ssdp.SSDPPlugin.java

License:Open Source License

public void createSockets() {
    try {/* ww w . j  a  v  a 2  s  . co  m*/
        logger.debug("Using network interface: {}; local address: {}", nic, localAddress);

        if (nic == null) {
            logger.error("Unable to determine local NIC; discovery may not work properly");
        }

        if (nic != null) {
            Bootstrap clientBootstrap = new Bootstrap().group(eventLoopGroup)
                    .channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }
                    }).localAddress(groupAddress).option(ChannelOption.IP_MULTICAST_IF, nic)
                    .option(ChannelOption.SO_REUSEADDR, true).handler(new SSDPInboundHandler(this));

            clientBootstrap.bind().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    multicastChannel = (NioDatagramChannel) channelFuture.channel();
                    multicastChannel.joinGroup(groupAddress, nic);
                }
            });
        }

        Bootstrap serverBootstrap = new Bootstrap().group(eventLoopGroup)
                .channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                    }
                }).localAddress(localAddress).option(ChannelOption.IP_MULTICAST_IF, nic)
                .option(ChannelOption.SO_REUSEADDR, true).handler(new SSDPInboundHandler(this));

        serverBootstrap.bind().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                localChannel = (NioDatagramChannel) channelFuture.channel();
                sendDiscoveryPacket();
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.advantageous.conekt.datagram.impl.DatagramSocketImpl.java

License:Open Source License

public DatagramSocketImpl(ConektInternal vertx, DatagramSocketOptions options) {
    super(vertx,/*from w  w w. ja  v a 2  s  . c  o  m*/
            createChannel(
                    options.isIpV6() ? io.advantageous.conekt.datagram.impl.InternetProtocolFamily.IPv6
                            : io.advantageous.conekt.datagram.impl.InternetProtocolFamily.IPv4,
                    new DatagramSocketOptions(options)),
            vertx.getOrCreateContext(), options);
    ContextImpl creatingContext = vertx.getContext();
    if (creatingContext != null && creatingContext.isMultiThreadedWorkerContext()) {
        throw new IllegalStateException("Cannot use DatagramSocket in a multi-threaded worker verticle");
    }
    channel().config().setOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
    context.nettyEventLoop().register(channel);
    channel.pipeline().addLast("handler", new DatagramServerHandler(this));
    channel().config().setMaxMessagesPerRead(1);
}

From source file:io.advantageous.conekt.datagram.impl.DatagramSocketImpl.java

License:Open Source License

private static NioDatagramChannel createChannel(
        io.advantageous.conekt.datagram.impl.InternetProtocolFamily family, DatagramSocketOptions options) {
    NioDatagramChannel channel;//  w w w.j  a  va2 s.c o m
    if (family == null) {
        channel = new NioDatagramChannel();
    } else {
        switch (family) {
        case IPv4:
            channel = new NioDatagramChannel(InternetProtocolFamily.IPv4);
            break;
        case IPv6:
            channel = new NioDatagramChannel(InternetProtocolFamily.IPv6);
            break;
        default:
            channel = new NioDatagramChannel();
        }
    }
    if (options.getSendBufferSize() != -1) {
        channel.config().setSendBufferSize(options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        channel.config().setReceiveBufferSize(options.getReceiveBufferSize());
        channel.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    channel.config().setReuseAddress(options.isReuseAddress());
    if (options.getTrafficClass() != -1) {
        channel.config().setTrafficClass(options.getTrafficClass());
    }
    channel.config().setBroadcast(options.isBroadcast());
    channel.config().setLoopbackModeDisabled(options.isLoopbackModeDisabled());
    if (options.getMulticastTimeToLive() != -1) {
        channel.config().setTimeToLive(options.getMulticastTimeToLive());
    }
    if (options.getMulticastNetworkInterface() != null) {
        try {
            channel.config()
                    .setNetworkInterface(NetworkInterface.getByName(options.getMulticastNetworkInterface()));
        } catch (SocketException e) {
            throw new IllegalArgumentException(
                    "Could not find network interface with name " + options.getMulticastNetworkInterface());
        }
    }
    return channel;
}

From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java

License:Apache License

private CompletableFuture<Void> bootstrapServer() {
    Bootstrap serverBootstrap = new Bootstrap().group(group)
            .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .handler(new SimpleChannelInboundHandler<Object>() {
                @Override/*from   w  w w  .ja v  a2s.c  o m*/
                public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                    // Nothing will be sent.
                }
            }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true);

    CompletableFuture<Void> future = new CompletableFuture<>();
    serverBootstrap.bind(localAddress).addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            serverChannel = f.channel();
            future.complete(null);
        } else {
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.atomix.cluster.messaging.impl.NettyBroadcastService.java

License:Apache License

private CompletableFuture<Void> bootstrapClient() {
    Bootstrap clientBootstrap = new Bootstrap().group(group)
            .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4))
            .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                @Override//ww  w  .j av a  2  s.c  om
                protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet)
                        throws Exception {
                    byte[] payload = new byte[packet.content().readInt()];
                    packet.content().readBytes(payload);
                    Message message = SERIALIZER.decode(payload);
                    Set<Consumer<byte[]>> listeners = NettyBroadcastService.this.listeners
                            .get(message.subject());
                    if (listeners != null) {
                        for (Consumer<byte[]> listener : listeners) {
                            listener.accept(message.payload());
                        }
                    }
                }
            }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true)
            .localAddress(localAddress.getPort());

    CompletableFuture<Void> future = new CompletableFuture<>();
    clientBootstrap.bind().addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            clientChannel = (DatagramChannel) f.channel();
            log.info("{} joining multicast group {} on port {}", localAddress.getHostName(),
                    groupAddress.getHostName(), groupAddress.getPort());
            clientChannel.joinGroup(groupAddress, iface).addListener(f2 -> {
                if (f2.isSuccess()) {
                    log.info("{} successfully joined multicast group {} on port {}", localAddress.getHostName(),
                            groupAddress.getHostName(), groupAddress.getPort());
                    future.complete(null);
                } else {
                    log.info("{} failed to join group {} on port {}", localAddress.getHostName(),
                            groupAddress.getHostName(), groupAddress.getPort());
                    future.completeExceptionally(f2.cause());
                }
            });
        } else {
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}

From source file:io.hekate.cluster.seed.multicast.MulticastSeedNodeProvider.java

License:Apache License

/**
 * Constructs new instance./*w  ww. ja v  a 2s .  c  om*/
 *
 * @param cfg Configuration.
 *
 * @throws UnknownHostException If failed to resolve multicast group address.
 */
public MulticastSeedNodeProvider(MulticastSeedNodeProviderConfig cfg) throws UnknownHostException {
    ConfigCheck check = ConfigCheck.get(getClass());

    check.notNull(cfg, "configuration");
    check.positive(cfg.getPort(), "port");
    check.nonNegative(cfg.getTtl(), "TTL");
    check.notEmpty(cfg.getGroup(), "multicast group");
    check.positive(cfg.getInterval(), "discovery interval");
    check.positive(cfg.getWaitTime(), "wait time");
    check.that(cfg.getInterval() < cfg.getWaitTime(), "discovery interval must be greater than wait time "
            + "[discovery-interval=" + cfg.getInterval() + ", wait-time=" + cfg.getWaitTime() + ']');

    InetAddress groupAddress = InetAddress.getByName(cfg.getGroup());

    check.isTrue(groupAddress.isMulticastAddress(),
            "address is not a multicast address [address=" + groupAddress + ']');

    group = new InetSocketAddress(groupAddress, cfg.getPort());
    ttl = cfg.getTtl();
    interval = cfg.getInterval();
    waitTime = cfg.getWaitTime();
    loopBackDisabled = cfg.isLoopBackDisabled();

    ipVer = group.getAddress() instanceof Inet6Address ? InternetProtocolFamily.IPv6
            : InternetProtocolFamily.IPv4;
}

From source file:io.jsync.datagram.impl.DefaultDatagramSocket.java

License:Open Source License

private static NioDatagramChannel createChannel(io.jsync.datagram.InternetProtocolFamily family) {
    if (family == null) {
        return new NioDatagramChannel();
    }//ww  w.j  av a 2s . co  m
    switch (family) {
    case IPv4:
        return new NioDatagramChannel(InternetProtocolFamily.IPv4);
    case IPv6:
        return new NioDatagramChannel(InternetProtocolFamily.IPv6);
    default:
        return new NioDatagramChannel();
    }
}

From source file:io.vertx.core.datagram.impl.DatagramSocketImpl.java

License:Open Source License

public DatagramSocketImpl(VertxInternal vertx, DatagramSocketOptions options) {
    super(vertx,//from ww  w  . java2 s  . c  o  m
            createChannel(
                    options.isIpV6() ? io.vertx.core.datagram.impl.InternetProtocolFamily.IPv6
                            : io.vertx.core.datagram.impl.InternetProtocolFamily.IPv4,
                    new DatagramSocketOptions(options)),
            vertx.getOrCreateContext());
    ContextImpl creatingContext = vertx.getContext();
    if (creatingContext != null && creatingContext.isMultiThreadedWorkerContext()) {
        throw new IllegalStateException("Cannot use DatagramSocket in a multi-threaded worker verticle");
    }
    channel().config().setOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
    context.nettyEventLoop().register(channel);
    if (options.getLogActivity()) {
        channel().pipeline().addLast("logging", new LoggingHandler());
    }
    channel.pipeline().addLast("handler", new DatagramServerHandler(this));
    channel().config().setMaxMessagesPerRead(1);
    channel().config().setAllocator(PartialPooledByteBufAllocator.INSTANCE);
    metrics = vertx.metricsSPI().createMetrics(this, (DatagramSocketOptions) options);
}

From source file:io.vertx.core.datagram.impl.DatagramSocketImpl.java

License:Open Source License

private static NioDatagramChannel createChannel(io.vertx.core.datagram.impl.InternetProtocolFamily family,
        DatagramSocketOptions options) {
    NioDatagramChannel channel;/* w ww  .jav a  2s . co m*/
    if (family == null) {
        channel = new NioDatagramChannel();
    } else {
        switch (family) {
        case IPv4:
            channel = new NioDatagramChannel(InternetProtocolFamily.IPv4);
            break;
        case IPv6:
            channel = new NioDatagramChannel(InternetProtocolFamily.IPv6);
            break;
        default:
            channel = new NioDatagramChannel();
        }
    }
    if (options.getSendBufferSize() != -1) {
        channel.config().setSendBufferSize(options.getSendBufferSize());
    }
    if (options.getReceiveBufferSize() != -1) {
        channel.config().setReceiveBufferSize(options.getReceiveBufferSize());
        channel.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(options.getReceiveBufferSize()));
    }
    channel.config().setReuseAddress(options.isReuseAddress());
    if (options.getTrafficClass() != -1) {
        channel.config().setTrafficClass(options.getTrafficClass());
    }
    channel.config().setBroadcast(options.isBroadcast());
    channel.config().setLoopbackModeDisabled(options.isLoopbackModeDisabled());
    if (options.getMulticastTimeToLive() != -1) {
        channel.config().setTimeToLive(options.getMulticastTimeToLive());
    }
    if (options.getMulticastNetworkInterface() != null) {
        try {
            channel.config()
                    .setNetworkInterface(NetworkInterface.getByName(options.getMulticastNetworkInterface()));
        } catch (SocketException e) {
            throw new IllegalArgumentException(
                    "Could not find network interface with name " + options.getMulticastNetworkInterface());
        }
    }
    return channel;
}

From source file:io.vertx.core.net.impl.transport.Transport.java

License:Open Source License

/**
 * @return a new datagram channel/*  ww  w  .  j ava  2s .  co  m*/
 */
public DatagramChannel datagramChannel(InternetProtocolFamily family) {
    switch (family) {
    case IPv4:
        return new NioDatagramChannel(InternetProtocolFamily.IPv4);
    case IPv6:
        return new NioDatagramChannel(InternetProtocolFamily.IPv6);
    default:
        throw new UnsupportedOperationException();
    }
}