List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:divconq.ctp.net.CtpServices.java
License:Open Source License
protected void stopSocketListener(SocketInfo info) { // tear down message port Channel ch = this.activelisteners.remove(info); try {//from w w w . j ava2 s . co m // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = ch.close().sync(); if (bfuture.isSuccess()) System.out.println("dcCtp Server unbound"); else System.out.println("dcCtp Server unable to unbind: " + bfuture.cause()); } catch (InterruptedException x) { System.out.println("dcCtp Server unable to unbind: " + x); } }
From source file:divconq.ctp.stream.CtpStreamDest.java
License:Open Source License
@Override public void operationComplete(ChannelFuture future) throws Exception { OperationContext.set(this.ctx); TaskRun trun = this.ctx.getTaskRun(); if (trun == null) { System.out.println("Error - stream task missing RUN"); } else if (future.isSuccess()) { if (this.finalFlag) trun.complete();/* www. java2 s . co m*/ else trun.resume(); } else { trun.kill("ERROR sending - DONE sending! " + future.cause()); } }
From source file:divconq.web.WebModule.java
License:Open Source License
public void goOnline() { this.listenlock.lock(); try {//w w w . ja v a 2s . c o m // don't try if already in online mode if (this.activelisteners.size() > 0) return; // typically we should have an extension, unless we are supporting RPC only // TODO if (WebSiteManager.instance.getDefaultExtension() == null) // log.warn(0, "No default extension for web server"); for (final XElement httpconfig : this.config.selectAll("HttpListener")) { final boolean secure = "True".equals(httpconfig.getAttribute("Secure")); int httpport = (int) StringUtil.parseInt(httpconfig.getAttribute("Port"), secure ? 443 : 80); // ------------------------------------------------- // message port // ------------------------------------------------- ServerBootstrap b = new ServerBootstrap(); // TODO consider using shared EventLoopGroup // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#25.0 b.group(Hub.instance.getEventLoopGroup()).channel(NioServerSocketChannel.class) .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator()) //.option(ChannelOption.SO_BACKLOG, 125) // this is probably not needed but serves as note to research .option(ChannelOption.TCP_NODELAY, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { SniHandler ssl = new SniHandler(WebModule.this.siteman); //SslHandler ssl = new SslHandler(WebModule.this.siteman.findSslContextFactory("root").getServerEngine()); pipeline.addLast("ssl", ssl); } //pipeline.addLast("codec-http", new HttpServerCodec()); //pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 262144)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // TODO maybe - but currently we selectively compress files which is more efficient // this can also be a cached & compressed response that way //pipeline.addLast("deflater", new HttpContentCompressor()); pipeline.addLast("handler", new ServerHandler(httpconfig, WebModule.this.siteman)); } }); try { // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = b.bind(httpport).sync(); if (bfuture.isSuccess()) { Logger.info("Web Server listening - now listening for HTTP on TCP port " + httpport); this.activelisteners.put(httpport, bfuture.channel()); } else Logger.error("Web Server unable to bind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.error("Web Server interrupted while binding: " + x); } catch (Exception x) { Logger.error("Web Server errored while binding: " + x); } } } finally { this.listenlock.unlock(); } this.siteman.online(); //for (IWebExtension ext : WebSiteManager.instance.extensions.values()) // ext.online(); }
From source file:divconq.web.WebModule.java
License:Open Source License
public void goOffline() { this.listenlock.lock(); try {// w w w. j a va 2 s .c o m // we don't want to listen anymore for (final Integer port : this.activelisteners.keySet()) { // tear down message port Channel ch = this.activelisteners.remove(port); try { // must wait here, both to keep the activelisteners listeners up to date // but also to make sure we don't release connectLock too soon ChannelFuture bfuture = ch.close().sync(); if (bfuture.isSuccess()) Logger.info("Web Server unbound"); else Logger.error("Web Server unable to unbind: " + bfuture.cause()); } catch (InterruptedException x) { Logger.error("Web Server unable to unbind: " + x); } } } finally { this.listenlock.unlock(); } }
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 {//from ww 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.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)! *///from www.j a v a 2s.co 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/>//www .j a v a 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:enetty.HexDumpProxyFrontendHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; System.out.println("uri: " + req.uri()); }/*from w w w .j a va 2s . com*/ if (outboundChannel.isActive()) { outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { // was able to flush out data, start to read the next chunk ctx.channel().read(); } else { future.channel().close(); } } }); } }
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/*from w ww. ja va 2s . com*/ 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.point.client.Client.java
License:Open Source License
/** * The method which creates the bootstrap to connect to the server. * It initializes the pipeline with all the required parameters and functions * for encoding, decoding, etc.//from ww w .j ava 2 s . c o m * It then sends the message to the server. * If the message is a Resource Request, then it also returns the received Resource Offer. * * @param message The message to be sent. * @return The received Resource Offer in case the message was a Resource Request. */ public static TmSdnMessages.TmSdnMessage.ResourceOfferMessage sendMessage(TmSdnMessages.TmSdnMessage message) { EventLoopGroup group = new NioEventLoopGroup(); TmSdnMessages.TmSdnMessage.ResourceOfferMessage resourceOffer = null; handler = new TmSdnClientHandler(message); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, false); //initialize the pipeline b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ProtobufVarint32FrameDecoder()); pipeline.addLast(new ProtobufDecoder(TmSdnMessages.TmSdnMessage.getDefaultInstance())); pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); pipeline.addLast(new ProtobufEncoder()); pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(5)); pipeline.addLast(handler); } }); // Make a new connection. ChannelFuture f = b.remoteAddress(serverIP, tcpPort).connect(); try { f.sync(); } catch (Exception e) { e.printStackTrace(); } //if message is resource request, then get the received resource offer and return it. if (f.isSuccess() && message.getType() == TmSdnMessages.TmSdnMessage.TmSdnMessageType.RR) { TmSdnMessages.TmSdnMessage.ResourceOfferMessage resp = handler.resultQueue.take(); if (resp != null) { resourceOffer = resp; } } //close the channel. f.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } return resourceOffer; }