List of usage examples for io.netty.channel.socket.nio NioDatagramChannel NioDatagramChannel
public NioDatagramChannel(DatagramChannel socket)
From source file:com.mpush.netty.udp.NettyUDPConnector.java
License:Apache License
private void createNioServer(Listener listener) { NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(ThreadNames.T_GATEWAY_WORKER)); eventLoopGroup.setIoRatio(100);/*from w ww . j a va 2 s . c o m*/ createServer(listener, eventLoopGroup, () -> new NioDatagramChannel(IPv4));//?Channel,?ipv6,ipv4? }
From source file:com.whizzosoftware.hobson.ssdp.SSDPPlugin.java
License:Open Source License
public void createSockets() { try {/*from w w w . j a v a 2 s . c o 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.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/* w w w . j a v a2s . co 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/*from ww w .java 2 s . co m*/ 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
@Override public void startDiscovery(String cluster, InetSocketAddress address) throws HekateException { log.info("Starting seed nodes discovery [cluster={}, {}]", cluster, ToString.formatProperties(this)); SeedNode thisNode = new SeedNode(address, cluster); try {// w w w . ja v a 2 s . com NetworkInterface nif = selectMulticastInterface(address); try { synchronized (mux) { if (isRegistered()) { throw new IllegalStateException( "Multicast seed node provider is already registered with another address " + "[existing=" + localNode + ']'); } ByteBuf discoveryMsg = prepareDiscovery(thisNode); ByteBuf seedNodeInfoBytes = prepareSeedNodeInfo(thisNode); localNode = thisNode; seedNodes = new HashSet<>(); eventLoop = new NioEventLoopGroup(1, new HekateThreadFactory("SeedNodeMulticast")); // Prepare common bootstrap options. Bootstrap bootstrap = new Bootstrap(); bootstrap.option(ChannelOption.SO_REUSEADDR, true); bootstrap.option(ChannelOption.IP_MULTICAST_TTL, ttl); bootstrap.option(ChannelOption.IP_MULTICAST_IF, nif); if (loopBackDisabled) { bootstrap.option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, true); if (DEBUG) { log.debug("Setting {} option to true", ChannelOption.IP_MULTICAST_LOOP_DISABLED); } } bootstrap.group(eventLoop); bootstrap.channelFactory(() -> new NioDatagramChannel(ipVer)); // Create a sender channel (not joined to a multicast group). bootstrap.localAddress(0); bootstrap.handler(createSenderHandler(thisNode)); ChannelFuture senderBind = bootstrap.bind(); DatagramChannel localSender = (DatagramChannel) senderBind.channel(); sender = localSender; senderBind.get(); // Create a listener channel and join to a multicast group. bootstrap.localAddress(group.getPort()); bootstrap.handler(createListenerHandler(thisNode, seedNodeInfoBytes)); ChannelFuture listenerBind = bootstrap.bind(); listener = (DatagramChannel) listenerBind.channel(); listenerBind.get(); log.info("Joining to a multicast group " + "[address={}, port={}, interface={}, ttl={}]", AddressUtils.host(group), group.getPort(), nif.getName(), ttl); listener.joinGroup(group, nif).get(); // Create a periodic task for discovery messages sending. discoveryFuture = eventLoop.scheduleWithFixedDelay(() -> { if (DEBUG) { log.debug("Sending discovery message [from={}]", thisNode); } DatagramPacket discovery = new DatagramPacket(discoveryMsg.copy(), group); localSender.writeAndFlush(discovery); }, 0, interval, TimeUnit.MILLISECONDS); } } catch (ExecutionException e) { cleanup(); throw new HekateException( "Failed to start a multicast seed nodes discovery [node=" + thisNode + ']', e.getCause()); } log.info("Will wait for seed nodes [timeout={}(ms)]", waitTime); Thread.sleep(waitTime); } catch (InterruptedException e) { cleanup(); Thread.currentThread().interrupt(); throw new HekateException( "Thread was interrupted while awaiting for multicast discovery [node=" + thisNode + ']', e); } log.info("Done waiting for seed nodes."); }
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 . com */ 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(); } }
From source file:org.codice.alliance.video.stream.mpegts.UdpStreamMonitor.java
License:Open Source License
private void runMulticastServer(Bootstrap bootstrap, NetworkInterface networkInterface, InetAddress inetAddress) { bootstrap.group(eventLoopGroup).channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4)) .handler(new Pipeline(udpStreamProcessor)).localAddress(inetAddress, monitoredPort) .option(ChannelOption.IP_MULTICAST_IF, networkInterface).option(ChannelOption.SO_REUSEADDR, true); try {/*from w ww . j a v a 2 s . c om*/ channelFuture = bootstrap.bind(monitoredPort).sync(); NioDatagramChannel ch = (NioDatagramChannel) channelFuture.channel(); ch.joinGroup(new InetSocketAddress(monitoredAddress, monitoredPort), networkInterface).sync(); } catch (InterruptedException e) { LOGGER.debug("interrupted while waiting for shutdown", e); } }
From source file:org.fiware.kiara.netty.NioDatagramChannelFactory.java
License:Open Source License
@Override public NioDatagramChannel newChannel() { try {// w ww .j a v a 2s. c o m return new NioDatagramChannel(ipFamily); } catch (Throwable t) { throw new ChannelException("Unable to create Channel from class NioDatagramChannel", t); } }
From source file:picoview.collectd.CollectClient.java
License:Apache License
@Override public void initialize() throws RuntimeException { NetworkInterface nic;//from w w w .j a v a 2s . c o m try { if (StringUtils.isBlank(nicName)) { nic = NetworkInterface.getByIndex(0); } else { nic = NetworkInterface.getByName(nicName); } } catch (SocketException exep) { throw new RuntimeException("unable to determine network interface to use", exep); } Bootstrap bs = new Bootstrap(); bs.option(ChannelOption.SO_BROADCAST, true); bs.option(ChannelOption.SO_REUSEADDR, true); bs.option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, false); bs.option(ChannelOption.SO_RCVBUF, 2048); bs.option(ChannelOption.IP_MULTICAST_TTL, 255); bs.group(new NioEventLoopGroup()); bs.channelFactory(new ChannelFactory<Channel>() { public Channel newChannel() { return new NioDatagramChannel(InternetProtocolFamily.IPv4); } }); bs.handler(new ChannelInitializer<DatagramChannel>() { @Override public void initChannel(DatagramChannel channel) throws Exception { channel.pipeline().addLast(new CollectChannelHandler()); } }); if (StringUtils.isBlank(multicastHost)) { multicastHost = "239.192.74.66"; } if (multicastPort <= 0) { multicastPort = 25826; } try { DatagramChannel dch = (DatagramChannel) bs.bind(multicastPort).sync().channel(); ChannelFuture cf = dch.joinGroup(new InetSocketAddress(multicastHost, multicastPort), nic).sync(); if (!cf.isSuccess()) { throw new RuntimeException("unable to join multicast group"); } } catch (InterruptedException exep) { throw new RuntimeException("unable to setup network for collect client", exep); } }
From source file:reactor.io.net.impl.netty.udp.NettyDatagramServer.java
License:Apache License
public NettyDatagramServer(@Nonnull Environment env, @Nonnull Dispatcher dispatcher, @Nullable InetSocketAddress listenAddress, @Nullable final NetworkInterface multicastInterface, @Nonnull final ServerSocketOptions options, @Nullable Codec<Buffer, IN, OUT> codec) { super(env, dispatcher, listenAddress, multicastInterface, options, codec); if (options instanceof NettyServerSocketOptions) { this.nettyOptions = (NettyServerSocketOptions) options; } else {// w ww .ja v a 2 s . c om this.nettyOptions = null; } if (null != nettyOptions && null != nettyOptions.eventLoopGroup()) { this.ioGroup = nettyOptions.eventLoopGroup(); } else { int ioThreadCount = getDefaultEnvironment().getIntProperty("reactor.udp.ioThreadCount", Environment.PROCESSORS); this.ioGroup = new NioEventLoopGroup(ioThreadCount, new NamedDaemonThreadFactory("reactor-udp-io")); } final InternetProtocolFamily family = toNettyFamily(options.protocolFamily()); this.bootstrap = new Bootstrap().group(ioGroup).option(ChannelOption.SO_RCVBUF, options.rcvbuf()) .option(ChannelOption.SO_SNDBUF, options.sndbuf()) .option(ChannelOption.SO_REUSEADDR, options.reuseAddr()).option(ChannelOption.AUTO_READ, false) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, options.timeout()) .channelFactory(new ChannelFactory<Channel>() { @Override public Channel newChannel() { return new NioDatagramChannel(family); } }); if (null != listenAddress) { bootstrap.localAddress(listenAddress); } else { bootstrap.localAddress(NetUtil.LOCALHOST, 3000); } if (null != multicastInterface) { bootstrap.option(ChannelOption.IP_MULTICAST_IF, multicastInterface); } }