List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java
License:Apache License
public void start() { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override//from w w w . jav a 2 s .c om public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)), new NettyRemotingServerHandler(serviceActivator)); } }); // Bind and start to accept incoming connections. Binds to all interfaces // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port ChannelFuture channel = b.bind(port); try { if (channel.await(2, TimeUnit.SECONDS)) { if (channel.isSuccess()) { port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort(); log.info("NettyRemotingServer started listening on port={}", port); return; } } } catch (InterruptedException e) { } throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port); }
From source file:com.baidu.jprotobuf.pbrpc.management.HttpServer.java
License:Apache License
public void start(int port) { serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override/* ww w .ja v a 2 s. co m*/ public void initChannel(SocketChannel ch) throws Exception { // server??httpResponse?HttpResponseEncoder? ch.pipeline().addLast(new HttpResponseEncoder()); // serverhttpRequest?HttpRequestDecoder? ch.pipeline().addLast(new HttpRequestDecoder()); ch.pipeline().addLast(new HttpServerInboundHandler(rpcServer)); } }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); serverBootstrap.bind(port).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = future.channel(); // TODO notifyStarted(); } else { // TODO notifyFailed(future.cause()); } } }); LOG.log(Level.INFO, "Http starting at port: " + port); }
From source file:com.baidu.jprotobuf.pbrpc.transport.ChannelPoolObjectFactory.java
License:Apache License
@Override public PooledObject<Connection> wrap(Connection obj) { Connection connection = fetchConnection(); InetSocketAddress address;/*from w ww . ja va 2 s . c o m*/ if (host == null) { address = new InetSocketAddress(port); } else { address = new InetSocketAddress(host, port); } ChannelFuture future = this.rpcClient.connect(address); // Wait until the connection is made successfully. future.awaitUninterruptibly(); if (!future.isSuccess()) { LOGGER.log(Level.SEVERE, "failed to get result from stp", future.cause()); } else { connection.setIsConnected(true); } future.addListener(new RpcChannelFutureListener(connection)); connection.setFuture(future); return new DefaultPooledObject<Connection>(connection); }
From source file:com.baidu.jprotobuf.pbrpc.transport.RpcChannelFutureListener.java
License:Apache License
public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { LOG.log(Level.WARNING, "build channel:" + future.channel() + " failed"); conn.setIsConnected(false);/*ww w .j a v a2 s . c o m*/ return; } RpcClientCallState requestState = null; while (null != (requestState = conn.consumeRequest())) { LOG.log(Level.FINEST, "[correlationId:" + requestState.getDataPackage().getRpcMeta().getCorrelationId() + "] send over from queue"); conn.getFuture().channel().writeAndFlush(requestState.getDataPackage()); } }
From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServer.java
License:Apache License
public void start(InetSocketAddress sa) { LOG.log(Level.INFO, "RPC starting at: " + sa); this.bind(sa).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = future.channel(); // TODO notifyStarted(); } else { // TODO notifyFailed(future.cause()); }/*from ww w .j a v a2 s . co m*/ } }); this.inetSocketAddress = sa; startTime = System.currentTimeMillis(); // check if need start http server if (rpcServerOptions.getHttpServerPort() > 0) { httpServer = new HttpServer(this); httpServer.start(rpcServerOptions.getHttpServerPort()); } }
From source file:com.barchart.netty.client.base.ConnectableBase.java
License:BSD License
@Override public Observable<T> connect() { if (transport == null) { throw new IllegalArgumentException("Transport cannot be null"); }/*from w w w . j a v a 2s .c o m*/ if (channelInitializer == null) { throw new IllegalArgumentException("Channel initializer cannot be null"); } log.debug("Client connecting to " + transport.address().toString()); changeState(Connectable.State.CONNECTING); final ChannelFuture future = bootstrap() // .group(group) // .handler(new ClientPipelineInitializer()) // .connect(); channel = future.channel(); final ReplaySubject<T> connectObs = ReplaySubject.create(); future.addListener(new ChannelFutureListener() { @SuppressWarnings("unchecked") @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { changeState(Connectable.State.CONNECT_FAIL); connectObs.onError(future.cause()); } else { connectObs.onNext((T) ConnectableBase.this); connectObs.onCompleted(); } } }); return connectObs; }
From source file:com.barchart.netty.server.stream.MulticastTransceiver.java
License:BSD License
/** * Join the multicast group address using the network interface associated * with the given address./*from w w w.ja v a2 s. co m*/ */ @Override public ChannelFuture listen(final SocketAddress address) { if (pipelineInit == null) { throw new IllegalStateException("No pipeline initializer has been provided, server would do nothing"); } // Kinda hacky, need to override bootstrap params based on passed // address final ChannelFuture future = bootstrap() // .option(ChannelOption.IP_MULTICAST_IF, bindInterface((InetSocketAddress) address)) // .localAddress(multicast.getPort()) // .remoteAddress(multicast) // .bind(); future.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { final NioDatagramChannel channel = (NioDatagramChannel) future.channel(); channel.joinGroup(multicast, channel.config().getOption(ChannelOption.IP_MULTICAST_IF)); } } }); serverChannels.add(future.channel()); return future; }
From source file:com.basho.riak.client.core.ConnectionPool.java
License:Apache License
private Channel doGetConnection() throws ConnectionFailedException { ChannelWithIdleTime cwi;//from ww w. j a v a 2 s.com 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;/*ww w . j a va2s . 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.chenyang.proxy.http.HttpRemoteForwardHandler.java
License:Apache License
public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg) throws Exception { remainMsgCount++;//from ww w . ja v a2 s. co m if (remainMsgCount <= 5) { remoteChannelCtx.read(); } HttpObject ho = (HttpObject) msg; if (ho instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) ho; httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE); } if (uaChannel.isActive()) { uaChannel.writeAndFlush(ho).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { remainMsgCount--; remoteChannelCtx.read(); } else { remoteChannelCtx.close(); } } }); } else { remoteChannelCtx.close(); } }