List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
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 {/* ww w .j a va2s. c om*/ 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.connection.EndPointClient.java
License:Apache License
/** * this is called by 2 threads. The startup thread, and the registration-in-progress thread * * NOTE: must be inside synchronize(bootstrapLock)! *//* w ww .j a va 2s . c o m*/ private void doRegistration() { BootstrapWrapper bootstrapWrapper = bootstrapIterator.next(); ChannelFuture future; if (connectionTimeout != 0) { // must be before connect bootstrapWrapper.bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout); } try { // UDP : When this is CONNECT, a udp socket will ONLY accept UDP traffic from the remote address (ip/port combo). // If the reply isn't from the correct port, then the other end will receive a "Port Unreachable" exception. future = bootstrapWrapper.bootstrap.connect(); future.await(connectionTimeout); } catch (Exception e) { String errorMessage = "Could not connect to the " + bootstrapWrapper.type + " server at " + bootstrapWrapper.address + " on port: " + bootstrapWrapper.port; if (logger.isDebugEnabled()) { // extra info if debug is enabled logger.error(errorMessage, e); } else { logger.error(errorMessage); } return; } if (!future.isSuccess()) { Throwable cause = future.cause(); // extra space here is so it aligns with "Connecting to server:" String errorMessage = "Connection refused :" + bootstrapWrapper.address + " at " + bootstrapWrapper.type + " port: " + bootstrapWrapper.port; if (cause instanceof java.net.ConnectException) { if (cause.getMessage().contains("refused")) { logger.error(errorMessage); } } else { logger.error(errorMessage, cause); } return; } logger.trace("Waiting for registration from server."); manageForShutdown(future); }
From source file:dorkbox.network.Server.java
License:Apache License
/** * Binds the server to the configured, underlying protocols. * <p/>/*from w w w. j a va 2 s .com*/ * 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:eu.heronnet.module.kad.net.ClientImpl.java
License:Open Source License
private void broadcastOnInterface(InterfaceAddress interfaceAddress, Messages.Request request) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast != null) { ByteString messageId = request.getMessageId(); udpBoostrap.handler(new ResponseHandler(messageId.toByteArray())); udpBoostrap.bind(0).addListener(new ChannelFutureListener() { @Override/*www.ja v a 2s. c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { final Channel channel = future.channel(); final ByteBuf requestBuffer = Unpooled.wrappedBuffer(request.toByteArray()); final DatagramPacket datagramPacket = new DatagramPacket(requestBuffer, new InetSocketAddress(broadcast, selfNodeProvider.getSelf().getPort())); channel.writeAndFlush(datagramPacket); channel.close(); logger.debug("completed operation: {}", future.toString()); } else { logger.error("Error in channel bootstrap: {}", future.cause().getMessage()); } } }); } }
From source file:eu.stratosphere.runtime.io.network.netty.OutboundConnectionQueue.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { writeAndFlushNextEnvelopeIfPossible(); } else if (future.cause() != null) { exceptionOccurred(future.cause()); } else {//from w ww . j a va2 s .c o m exceptionOccurred(new Exception("Envelope send aborted.")); } }
From source file:freddo.dtalk2.client.netty.NettyClient.java
License:Apache License
public NettyClient(String name, URI uri) { mName = name;/*from w ww . ja va2 s. co m*/ // connect... EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); String protocol = uri.getScheme(); if (!"ws".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } HttpHeaders customHeaders = new DefaultHttpHeaders(); // customHeaders.add("MyHeader", "MyValue"); // Connect with V13 (RFC 6455 aka HyBi-17). final NettyClientHandler handler = new NettyClientHandler(this, WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, customHeaders)); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(8192)); pipeline.addLast("ws-handler", handler); } }); LOG.debug("WebSocket Client connecting..."); mChannel = b.connect(uri.getHost(), uri.getPort()) .addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (!f.isSuccess()) { LOG.debug("Connection error", f.cause()); } } }).sync().channel(); LOG.debug("Handshake..."); handler.handshakeFuture().sync(); } catch (Exception e) { LOG.debug("Error: {}", e.getMessage()); // e.printStackTrace(); group.shutdownGracefully(); group = null; } }
From source file:gash.router.server.queue.CommandOutboundAppWorker.java
License:Apache License
@Override public void run() { Channel conn = sq.channel;/*w w w. j a va 2 s. c om*/ if (conn == null || !conn.isOpen()) { PerChannelCommandQueue.logger.error("connection missing, no outboundWork communication"); return; } while (true) { if (!forever && sq.outboundWork.size() == 0) break; try { // block until a message is enqueued GeneratedMessage msg = sq.outboundWork.take(); if (conn.isWritable()) { boolean rtn = false; if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) { ChannelFuture cf = sq.channel.writeAndFlush(msg); logger.info("Server--sending -- command -- response"); // blocks on write - use listener to be async cf.awaitUninterruptibly(); logger.debug("Written to channel"); rtn = cf.isSuccess(); if (!rtn) { System.out.println("Sending failed " + rtn + "{Reason:" + cf.cause() + "}"); sq.outboundWork.putFirst(msg); } else logger.info("Message Sent"); } } else sq.outboundWork.putFirst(msg); } catch (InterruptedException ie) { break; } catch (Exception e) { logger.error("Unexpected communcation failure", e); break; } } if (!forever) { logger.debug("connection queue closing"); } }
From source file:gash.router.server.queue.GlobalCommandOutboundAppWorker.java
License:Apache License
@Override public void run() { Channel conn = sq.channel;/*from ww w . ja va2 s .c o m*/ if (conn == null || !conn.isOpen()) { PerChannelGlobalCommandQueue.logger.error("connection missing, no outboundWork communication"); return; } while (true) { if (!forever && sq.outboundWork.size() == 0) break; try { // block until a message is enqueued GeneratedMessage msg = sq.outboundWork.take(); if (conn.isWritable()) { boolean rtn = false; if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) { ChannelFuture cf = sq.channel.writeAndFlush(msg); logger.info("Server--sending -- command -- response"); // blocks on write - use listener to be async cf.awaitUninterruptibly(); logger.debug("Written to channel"); rtn = cf.isSuccess(); if (!rtn) { System.out.println("Sending failed " + rtn + "{Reason:" + cf.cause() + "}"); sq.outboundWork.putFirst(msg); } else logger.info("Message Sent"); } } else sq.outboundWork.putFirst(msg); } catch (InterruptedException ie) { break; } catch (Exception e) { logger.error("Unexpected communcation failure", e); break; } } if (!forever) { logger.info("connection queue closing"); } }
From source file:gash.router.server.queue.WorkOutboundAppWorker.java
License:Apache License
@Override public void run() { Channel conn = sq.channel;//from w w w . j a va 2s .c om if (conn == null || !conn.isOpen()) { PerChannelWorkQueue.logger.error("connection missing, no outboundWork communication"); return; } while (true) { if (!forever && sq.outbound.size() == 0) break; try { // block until a message is enqueued GeneratedMessage msg = sq.outbound.take(); if (conn.isWritable()) { boolean rtn = false; if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) { ChannelFuture cf = sq.channel.writeAndFlush((Work.WorkRequest) msg); logger.info("Server--sending -- work-- response"); // blocks on write - use listener to be async cf.awaitUninterruptibly(); logger.debug("Written to channel"); rtn = cf.isSuccess(); if (!rtn) { logger.error("Sending failed " + rtn + "{Reason:" + cf.cause() + "}"); sq.outbound.putFirst(msg); } else logger.info("Message Sent"); } } else sq.outbound.putFirst(msg); } catch (InterruptedException ie) { break; } catch (Exception e) { logger.error("Unexpected communcation failure", e); break; } } if (!forever) { logger.debug("connection queue closing"); } }
From source file:gedi.remote.RemoteConnections.java
License:Apache License
/** * Connects to the given server; the mechanics is as follows: * <br/>//from w ww . j a v a 2 s . co m * The initChannel consumer is supposed to register channel handlers (called upon channel.registered) * <br/> * Depending on the outcome of the Bootrap.connect method, either the errorHandler or the connectedHandler is called. * <br/> * If the connection is lost, the closedHandler is called. * <br/> * If you want to cancel the connection attempt, invoke cancel on the returned ChannelFuture. If you want to terminate the connection, use the * channel object from the connectedHandler. * <br /> * If the channel is unregistered, the added flag is reset for all handlers bound to the channel pipeline (important if you want to reuse * the handlers added by the initChannel consumer). * * @param uri * @param initChannel * @param errorHandler * @param connectedHandler * @param closedHandler * @return */ public ChannelFuture connect(URI uri, Consumer<SocketChannel> initChannel, Consumer<Throwable> errorHandler, Consumer<SocketChannel> connectedHandler, Runnable closedHandler) { final Protocol protocol = ProtocolExtensionPoint.getInstance().get(ExtensionContext.emptyContext(), uri.getScheme()); if (protocol == null) throw new RuntimeException("Protocol " + uri.getScheme() + " unknown!"); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); protocol.setCodecs(pipeline); initChannel.accept(ch); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { pipeline.addLast(new ConfigLoggingHandler(ConfigLoggingHandler.LogLevel.INFO)); connectedHandler.accept(ch); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); closedHandler.run(); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().iterator().forEachRemaining((e) -> Workarounds.removeAdded(e.getValue())); super.channelUnregistered(ctx); } }); } }); // Make a new connection and wait until closed. ChannelFuture f = b.connect(uri.getHost(), uri.getPort() == -1 ? protocol.getDefaultPort() : uri.getPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause != null) { log.log(Level.INFO, "Connection failed to server " + uri + ": " + cause.getMessage()); try { errorHandler.accept(cause); } finally { group.shutdownGracefully(); } } else { log.log(Level.INFO, "Client connected to server " + uri); future.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.log(Level.INFO, "Connection closed to server " + uri); group.shutdownGracefully(); } }); } } }); return f; }