List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.barchart.http.server.HttpServer.java
License:BSD License
/** * Start the server with the configuration settings provided. *//* w w w . j av a 2 s . c o m*/ public ChannelFuture listen() { if (config == null) { throw new IllegalStateException("Server has not been configured"); } if (serverChannel != null) { throw new IllegalStateException("Server is already running."); } final ChannelFuture future = new ServerBootstrap() // .group(config.parentGroup(), config.childGroup()) // .channel(NioServerSocketChannel.class) // .localAddress(config.address()) // .childHandler(new HttpServerChannelInitializer()) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_SNDBUF, 262144) // .option(ChannelOption.SO_RCVBUF, 262144) // .bind(); serverChannel = future.channel(); return future; }
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 ww . ja v a 2 s . co 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.base.AbstractServer.java
License:BSD License
@Override public ChannelFuture listen(final SocketAddress address) { shutdownFuture = new DefaultPromise<T>(GlobalEventExecutor.INSTANCE); final ChannelFuture future = bootstrap().bind(address); serverChannels.add(future.channel()); return future; }
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 www .ja v a2 s . com */ @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.base.research.socket.netty.Client.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {//from w w w. j a v a 2 s. co m Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // ch.pipeline().addLast(new TimeDecode()); ch.pipeline().addLast(new TestDecode2()); // ch.pipeline().addLast(new TestEncode()); ch.pipeline().addLast(new TestEncode2()); ch.pipeline().addLast(new ClientHandler()); } }); // Make the connection attempt. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
From source file:com.base.research.socket.netty.Server.java
License:Apache License
public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w. j a va 2s . co m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // ch.pipeline().addLast(new TimeDecode()); ch.pipeline().addLast(new TestDecode2()); // ch.pipeline().addLast(new TestEncode()); ch.pipeline().addLast(new TestEncode2()); ch.pipeline().addLast(new ServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to // gracefully // shut down your server. f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.basho.riak.client.core.ConnectionPool.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { // Because we aren't storing raw channels in available we just throw // these in the recentlyClosed as an indicator. We'll leave it up // to the healthcheck task to purge the available queue of dead // connections and make decisions on what to do recentlyClosed.add(new ChannelWithIdleTime(future.channel())); logger.debug("Channel closed; {}:{} {}", remoteAddress, port, protocol); }
From source file:com.basho.riak.client.core.ConnectionPool.java
License:Apache License
private Channel doGetConnection() throws ConnectionFailedException { ChannelWithIdleTime cwi;// w w w. jav 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(); // 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;// w w w .java 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.beeswax.http.server.HttpServer.java
License:Apache License
public void run() throws InterruptedException { // Create event loop groups. One for incoming connections handling and // second for handling actual event by workers final NioEventLoopGroup bossGroup = new NioEventLoopGroup(serverConfig.bossGroupSize); final NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from ww w . j ava 2 s . co m*/ ServerBootstrap bootStrap = new ServerBootstrap(); bootStrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) // SO_BACKLOG : The maximum queue length for incoming connections. .option(ChannelOption.SO_BACKLOG, serverConfig.backlogSize) // TCP_NODELAY: option to disable Nagle's algorithm to achieve lower latency on every packet sent .option(ChannelOption.TCP_NODELAY, serverConfig.tcpNodelay) // SO_KEEPALIVE: option to enable keep-alive packets for a socket connection .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.keepAlive) .childHandler(new HttpServerChannelInitializer(serverConfig, handlerFactory)); // bind to port final ChannelFuture channelFuture = bootStrap.bind(serverConfig.port).sync(); // Wait until the server socket is closed. channelFuture.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }