List of usage examples for io.netty.channel ChannelFuture await
@Override
ChannelFuture await() throws InterruptedException;
From source file:bridgempp.bot.wrapper.BotWrapper.java
private static void botInitialize(File botConfig) { try {/* w w w. ja v a2 s .c om*/ Properties botProperties = new Properties(); if (!botConfig.exists()) { botConfig.createNewFile(); } botProperties.load(new FileInputStream(botConfig)); String botClass = botProperties.getProperty("botClass"); if (botClass == null) { writeDefaultConfig(botProperties); throw new UnsupportedOperationException( "Bot Class is null, cannot execute BridgeMPP server commands"); } Bot bot = (Bot) Class.forName(botClass).newInstance(); bot.initializeBot(); String serverAddress = botProperties.getProperty("serverAddress"); int portNumber = Integer.parseInt(botProperties.getProperty("serverPort")); if (serverAddress == null) { writeDefaultConfig(botProperties); throw new UnsupportedOperationException( "Server Address is null, cannot execute BridgeMPP server commands"); } ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(serverAddress, portNumber)); byte[] protocol = new byte[1]; protocol[0] = 0x32; channelFuture.await(); channelFuture.channel().writeAndFlush(Unpooled.wrappedBuffer(protocol)); channelFuture.channel().pipeline().addLast("frameDecoder", new ProtobufVarint32FrameDecoder()); channelFuture.channel().pipeline().addLast("protobufDecoder", new ProtobufDecoder(ProtoBuf.Message.getDefaultInstance())); channelFuture.channel().pipeline().addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender()); channelFuture.channel().pipeline().addLast("protobufEncoder", new ProtobufEncoder()); channelFuture.channel().pipeline().addLast(new IncommingMessageHandler(bot)); bot.channelFuture = channelFuture; bot.setProperties(botProperties); String serverKey = botProperties.getProperty("serverKey"); if (serverKey == null) { writeDefaultConfig(botProperties); throw new UnsupportedOperationException( "Server Key is null, cannot execute BridgeMPP server commands"); } printCommand("!usekey " + serverKey, bot); String botAlias = botProperties.getProperty("botname"); if (botAlias != null) { printCommand("!createalias " + botAlias, bot); } bot.name = botAlias; String[] groups = botProperties.getProperty("groups").split("; "); for (int i = 0; i < groups.length; i++) { printCommand("!subscribegroup " + groups[i], bot); } System.out.println("Joined " + groups.length + " groups"); } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException | InterruptedException ex) { Logger.getLogger(BotWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.basho.riak.client.core.ConnectionPool.java
License:Apache License
private Channel doGetConnection() throws ConnectionFailedException { ChannelWithIdleTime cwi;/*from w w w .j a v a 2s . co m*/ while ((cwi = available.poll()) != null) { Channel channel = cwi.getChannel(); // If the channel from available is closed, try again. This will result in // the caller always getting a connection or an exception. If closed // the channel is simply discarded so this also acts as a purge // for dead channels during a health check. if (channel.isOpen()) { return channel; } } ChannelFuture f = bootstrap.connect(); // Any channels that don't connect will trigger a close operation as well f.channel().closeFuture().addListener(this); try { f.await(); } catch (InterruptedException ex) { logger.info("Thread interrupted waiting for new connection to be made; {}", remoteAddress); Thread.currentThread().interrupt(); throw new ConnectionFailedException(ex); } if (!f.isSuccess()) { logger.error("Connection attempt failed: {}:{}; {}", remoteAddress, port, f.cause()); throw new ConnectionFailedException(f.cause()); } return f.channel(); }
From source file:com.basho.riak.client.core.RiakNode.java
License:Apache License
private Channel doGetConnection() throws ConnectionFailedException { ChannelWithIdleTime cwi;//from w ww . ja v a 2s .c o m while ((cwi = available.poll()) != null) { Channel channel = cwi.getChannel(); // If the channel from available is closed, try again. This will result in // the caller always getting a connection or an exception. If closed // the channel is simply discarded so this also acts as a purge // for dead channels during a health check. if (channel.isOpen()) { return channel; } } ChannelFuture f = bootstrap.connect(); try { f.await(); } catch (InterruptedException ex) { logger.error("Thread interrupted waiting for new connection to be made; {}", remoteAddress); Thread.currentThread().interrupt(); throw new ConnectionFailedException(ex); } if (!f.isSuccess()) { logger.error("Connection attempt failed: {}:{}; {}", remoteAddress, port, f.cause()); consecutiveFailedConnectionAttempts.incrementAndGet(); throw new ConnectionFailedException(f.cause()); } consecutiveFailedConnectionAttempts.set(0); Channel c = f.channel(); if (trustStore != null) { SSLContext context; try { context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); context.init(null, tmf.getTrustManagers(), null); } catch (Exception ex) { c.close(); logger.error("Failure configuring SSL; {}:{} {}", remoteAddress, port, ex); throw new ConnectionFailedException(ex); } SSLEngine engine = context.createSSLEngine(); Set<String> protocols = new HashSet<String>(Arrays.asList(engine.getSupportedProtocols())); if (protocols.contains("TLSv1.2")) { engine.setEnabledProtocols(new String[] { "TLSv1.2" }); logger.debug("Using TLSv1.2"); } else if (protocols.contains("TLSv1.1")) { engine.setEnabledProtocols(new String[] { "TLSv1.1" }); logger.debug("Using TLSv1.1"); } engine.setUseClientMode(true); RiakSecurityDecoder decoder = new RiakSecurityDecoder(engine, username, password); c.pipeline().addFirst(decoder); try { DefaultPromise<Void> promise = decoder.getPromise(); promise.await(); if (promise.isSuccess()) { logger.debug("Auth succeeded; {}:{}", remoteAddress, port); } else { c.close(); logger.error("Failure during Auth; {}:{} {}", remoteAddress, port, promise.cause()); throw new ConnectionFailedException(promise.cause()); } } catch (InterruptedException e) { c.close(); logger.error("Thread interrupted during Auth; {}:{}", remoteAddress, port); Thread.currentThread().interrupt(); throw new ConnectionFailedException(e); } } return c; }
From source file:com.github.mrstampy.pprspray.core.streamer.AbstractMediaStreamer.java
License:Open Source License
/** * Send data.//from w ww .j a va 2 s . co m * * @param data * the data * @throws Exception * the exception */ protected void sendData(byte[] data) throws Exception { ChannelFuture cf = streamer.stream(data); cf.await(); }
From source file:com.magnet.yak.load.NettyClient.java
License:Apache License
public static void main(String[] args) throws Exception { String host = "54.148.43.16"; int port = 5222; EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w w w .j a v a 2 s .c o m*/ Bootstrap b = new Bootstrap(); // (1) b.group(workerGroup); // (2) b.channel(NioSocketChannel.class); // (3) b.option(ChannelOption.SO_KEEPALIVE, true); // (4) b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new XMPPHandler()); } }); ChannelFuture f = b.connect(host, port).sync(); // (5) f.await(); Channel channel = f.channel(); LOGGER.trace("main : Writing {}"); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); } }
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 . j a v a 2s .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.Server.java
License:Apache License
/** * Binds the server to the configured, underlying protocols. * <p/>// w ww . j a v a 2s .co m * This is a more advanced method, and you should consider calling <code>bind()</code> instead. * * @param blockUntilTerminate * will BLOCK until the server stop method is called, and if you want to continue running code after this method * invocation, bind should be called in a separate, non-daemon thread - or with false as the parameter. */ @SuppressWarnings("AutoBoxing") public void bind(boolean blockUntilTerminate) { // make sure we are not trying to connect during a close or stop event. // This will wait until we have finished starting up/shutting down. synchronized (shutdownInProgress) { } // The bootstraps will be accessed ONE AT A TIME, in this order! ChannelFuture future; // LOCAL if (localBootstrap != null) { try { future = localBootstrap.bind(); future.await(); } catch (InterruptedException e) { throw new IllegalArgumentException( "Could not bind to LOCAL address '" + localChannelName + "' on the server.", e); } if (!future.isSuccess()) { throw new IllegalArgumentException( "Could not bind to LOCAL address '" + localChannelName + "' on the server.", future.cause()); } logger.info("Listening on LOCAL address: [{}]", localChannelName); manageForShutdown(future); } // TCP if (tcpBootstrap != null) { // Wait until the connection attempt succeeds or fails. try { future = tcpBootstrap.bind(); future.await(); } catch (Exception e) { stop(); throw new IllegalArgumentException( "Could not bind to address " + hostName + " TCP port " + tcpPort + " on the server.", e); } if (!future.isSuccess()) { stop(); throw new IllegalArgumentException( "Could not bind to address " + hostName + " TCP port " + tcpPort + " on the server.", future.cause()); } logger.info("TCP server listen address [{}:{}]", hostName, tcpPort); manageForShutdown(future); } // UDP if (udpBootstrap != null) { // Wait until the connection attempt succeeds or fails. try { future = udpBootstrap.bind(); future.await(); } catch (Exception e) { throw new IllegalArgumentException( "Could not bind to address " + hostName + " UDP port " + udpPort + " on the server.", e); } if (!future.isSuccess()) { throw new IllegalArgumentException( "Could not bind to address " + hostName + " UDP port " + udpPort + " on the server.", future.cause()); } logger.info("UDP server listen address [{}:{}]", hostName, udpPort); manageForShutdown(future); } isRunning = true; // we now BLOCK until the stop method is called. // if we want to continue running code in the server, bind should be called in a separate, non-daemon thread. if (blockUntilTerminate) { waitForShutdown(); } }
From source file:io.grpc.netty.NettyClientHandlerTest.java
License:Apache License
@Test public void nonExistentStream() throws Exception { Status status = Status.INTERNAL.withDescription("zz"); lifecycleManager.notifyShutdown(status); // Stream creation can race with the transport shutting down, with the create command already // enqueued.// ww w . ja va 2 s .c om ChannelFuture future1 = createStream(); future1.await(); assertNotNull(future1.cause()); assertThat(Status.fromThrowable(future1.cause()).getCode()).isEqualTo(status.getCode()); ChannelFuture future2 = enqueue(new CancelClientStreamCommand(streamTransportState, status)); future2.sync(); }
From source file:io.grpc.netty.NettyServer.java
License:Apache License
@Override public void start(ServerListener serverListener) throws IOException { listener = checkNotNull(serverListener, "serverListener"); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup);/* ww w . j a va 2s.c o m*/ b.channelFactory(channelFactory); // For non-socket based channel, the option will be ignored. b.option(SO_BACKLOG, 128); b.childOption(SO_KEEPALIVE, true); if (channelOptions != null) { for (Map.Entry<ChannelOption<?>, ?> entry : channelOptions.entrySet()) { @SuppressWarnings("unchecked") ChannelOption<Object> key = (ChannelOption<Object>) entry.getKey(); b.childOption(key, entry.getValue()); } } b.childHandler(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel ch) { ChannelPromise channelDone = ch.newPromise(); long maxConnectionAgeInNanos = NettyServer.this.maxConnectionAgeInNanos; if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) { // apply a random jitter of +/-10% to max connection age maxConnectionAgeInNanos = (long) ((.9D + Math.random() * .2D) * maxConnectionAgeInNanos); } NettyServerTransport transport = new NettyServerTransport(ch, channelDone, protocolNegotiator, streamTracerFactories, transportTracerFactory.create(), maxStreamsPerConnection, flowControlWindow, maxMessageSize, maxHeaderListSize, keepAliveTimeInNanos, keepAliveTimeoutInNanos, maxConnectionIdleInNanos, maxConnectionAgeInNanos, maxConnectionAgeGraceInNanos, permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos); ServerTransportListener transportListener; // This is to order callbacks on the listener, not to guard access to channel. synchronized (NettyServer.this) { if (channel != null && !channel.isOpen()) { // Server already shutdown. ch.close(); return; } // `channel` shutdown can race with `ch` initialization, so this is only safe to increment // inside the lock. eventLoopReferenceCounter.retain(); transportListener = listener.transportCreated(transport); } /** * Releases the event loop if the channel is "done", possibly due to the channel closing. */ final class LoopReleaser implements ChannelFutureListener { private boolean done; @Override public void operationComplete(ChannelFuture future) throws Exception { if (!done) { done = true; eventLoopReferenceCounter.release(); } } } transport.start(transportListener); ChannelFutureListener loopReleaser = new LoopReleaser(); channelDone.addListener(loopReleaser); ch.closeFuture().addListener(loopReleaser); } }); // Bind and start to accept incoming connections. ChannelFuture future = b.bind(address); try { future.await(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted waiting for bind"); } if (!future.isSuccess()) { throw new IOException("Failed to bind", future.cause()); } channel = future.channel(); Future<?> channelzFuture = channel.eventLoop().submit(new Runnable() { @Override public void run() { InternalInstrumented<SocketStats> listenSocket = new ListenSocket(channel); listenSocketStats.set(listenSocket); channelz.addListenSocket(listenSocket); } }); try { channelzFuture.await(); } catch (InterruptedException ex) { throw new RuntimeException("Interrupted while registering listen socket to channelz", ex); } }
From source file:net.hasor.rsf.remoting.transport.customer.InnerClientManager.java
License:Apache License
private synchronized AbstractRsfClient connSocket(final Address hostAddress) { final URL hostURL = hostAddress.getAddress(); Bootstrap boot = new Bootstrap(); boot.group(this.rsfContext.getLoopGroup()); boot.channel(NioSocketChannel.class); boot.option(ChannelOption.SO_KEEPALIVE, true); boot.handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { Channel channel = ch.pipeline().channel(); NetworkConnection.initConnection(hostURL, channel); LoggerHelper.logInfo("initConnection connect %s.", hostURL); //// w ww . j a v a2 s .c o m ch.pipeline().addLast(new RSFCodec(), new InnerRsfCustomerHandler(getRequestManager())); } }); ChannelFuture future = null; SocketAddress remote = new InetSocketAddress(hostURL.getHost(), hostURL.getPort()); LoggerHelper.logInfo("connect to %s ...", hostURL); future = boot.connect(remote); try { future.await(); } catch (InterruptedException e) { LoggerHelper.logSevere("connect to %s failure , %s", hostURL, e.getMessage()); return null; } if (future.isSuccess() == true) { LoggerHelper.logInfo("remote %s connected.", hostURL); NetworkConnection conn = NetworkConnection.getConnection(future.channel()); return new InnerRsfClient(this.getRequestManager(), conn); } // try { LoggerHelper.logSevere("connect to %s failure , %s", hostURL, future.cause().getMessage()); future.channel().close().await(); } catch (InterruptedException e) { LoggerHelper.logSevere("close connect(%s) failure , %s", hostURL, e.getMessage()); } return null; }