List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.vmware.xenon.common.http.netty.NettyChannelPool.java
License:Open Source License
/** * When using HTTP/2, we have to wait for the settings to be negotiated before we can send * data. We wait for a promise that comes from the HTTP client channel pipeline *//*from w ww . java2s. c o m*/ private void waitForSettings(Channel ch, NettyChannelContext contextFinal, Operation request, NettyChannelGroup group) { ChannelPromise settingsPromise = ch.attr(NettyChannelContext.SETTINGS_PROMISE_KEY).get(); settingsPromise.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // retrieve pending operations List<Operation> pendingOps = new ArrayList<>(); synchronized (group) { contextFinal.setOpenInProgress(false); contextFinal.setChannel(future.channel()).setOperation(request); pendingOps.addAll(group.pendingRequests); group.pendingRequests.clear(); } sendAfterConnect(future.channel(), contextFinal, request, group); // trigger pending operations for (Operation pendingOp : pendingOps) { pendingOp.setSocketContext(contextFinal); pendingOp.complete(); } } else { returnOrClose(contextFinal, true); fail(request, future.cause()); } } }); }
From source file:com.wangsan.study.netty.codec.serializable.netty.SubReqClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO//ww w . ja va 2 s . c o m EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // max? new ObjectDecoder(1024, ClassResolvers.cacheDisabled(this.getClass().getClassLoader()))); ch.pipeline().addLast(new ObjectEncoder()); ch.pipeline().addLast(new SubReqClientHandler()); } }); // ?? ChannelFuture f = b.connect(host, port).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:com.weibo.api.motan.transport.netty.NettyChannel.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri()); return true; }//from w ww .j ava 2 s . c om try { ChannelFuture channleFuture = nettyClient.getBootstrap() .connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort())); long start = System.currentTimeMillis(); int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException( "NettyClient init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } // ??connectTimeout boolean result = channleFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS); boolean success = channleFuture.isSuccess(); if (result && success) { channel = channleFuture.channel(); if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) channel.localAddress(); } state = ChannelState.ALIVE; return true; } boolean connected = false; if (channleFuture.channel() != null) { connected = channleFuture.channel().isActive(); } if (channleFuture.cause() != null) { channleFuture.cancel(false); throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channleFuture.cause()); } else { channleFuture.cancel(false); throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected); } } catch (MotanServiceException e) { throw e; } catch (Exception e) { throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e); } finally { if (!state.isAliveState()) { nettyClient.incrErrorCount(); } } }
From source file:com.weibo.api.motan.transport.netty.NettyServer.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("NettyServer ServerChannel already Open: url=" + url); return true; }/*ww w.j ava2 s .c om*/ LoggerUtil.info("NettyServer ServerChannel start Open: url=" + url); initServerBootstrap(); ChannelFuture channelFuture = bootstrap.bind(url.getPort()); serverChannel = (ServerChannel) channelFuture.channel(); state = ChannelState.ALIVE; StatsUtil.registryStatisticCallback(this); LoggerUtil.info("NettyServer ServerChannel finish Open: url=" + url); return state.isAliveState(); }
From source file:com.weibo.api.motan.transport.netty4.client.NettyChannel.java
License:Apache License
@Override public synchronized boolean open() { if (isAvailable()) { LoggerUtil.warn("the channel already open, local: " + localAddress + " remote: " + remoteAddress + " url: " + nettyClient.getUrl().getUri()); return true; }// ww w . j a v a 2 s. c o m try { ChannelFuture channelFuture = nettyClient.getBootstrap() .connect(new InetSocketAddress(nettyClient.getUrl().getHost(), nettyClient.getUrl().getPort())); long start = System.currentTimeMillis(); int timeout = nettyClient.getUrl().getIntParameter(URLParamType.connectTimeout.getName(), URLParamType.connectTimeout.getIntValue()); if (timeout <= 0) { throw new MotanFrameworkException( "Netty4Client init Error: timeout(" + timeout + ") <= 0 is forbid.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } // ??connectTimeout boolean result = channelFuture.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS); boolean success = channelFuture.isSuccess(); if (result && success) { channel = channelFuture.channel(); if (channel.localAddress() != null && channel.localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) channel.localAddress(); } state = ChannelState.ALIVE; return true; } boolean connected = false; if (channelFuture.channel() != null) { connected = channelFuture.channel().isOpen(); } if (channelFuture.cause() != null) { channelFuture.cancel(true); throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri() + ", result: " + result + ", success: " + success + ", connected: " + connected, channelFuture.cause()); } else { channelFuture.cancel(true); throw new MotanServiceException("NettyChannel connect to server timeout url: " + nettyClient.getUrl().getUri() + ", cost: " + (System.currentTimeMillis() - start) + ", result: " + result + ", success: " + success + ", connected: " + connected); } } catch (MotanServiceException e) { throw e; } catch (Exception e) { throw new MotanServiceException( "NettyChannel failed to connect to server, url: " + nettyClient.getUrl().getUri(), e); } finally { if (!state.isAliveState()) { nettyClient.incrErrorCount(); } } }
From source file:com.weibo.api.motan.transport.netty4.http.Netty4HttpServer.java
License:Apache License
@Override public boolean open() { if (isAvailable()) { return true; }/*from w w w . j a va 2 s.c om*/ if (channel != null) { channel.close(); } if (bossGroup == null) { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); } boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue()); // TODO max connection protect int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue()); int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), 500); int minWorkerThread = 0, maxWorkerThread = 0; if (shareChannel) { minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER); } else { minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER); maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER); } final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue()); final NettyHttpRequestHandler handler = new NettyHttpRequestHandler(this, messageHandler, new ThreadPoolExecutor(minWorkerThread, maxWorkerThread, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(workerQueueSize))); 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("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(maxContentLength)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("serverHandler", handler); } }).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, false); ChannelFuture f; try { f = b.bind(url.getPort()).sync(); channel = f.channel(); } catch (InterruptedException e) { LoggerUtil.error("init http server fail.", e); return false; } state = ChannelState.ALIVE; StatsUtil.registryStatisticCallback(this); LoggerUtil.info("Netty4HttpServer ServerChannel finish Open: url=" + url); return true; }
From source file:com.weibo.yar.yarserver.NettyYarServer.java
License:Apache License
public void start(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {// w w w . j av a 2 s . com 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("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("serverHandler", new HttpServerHandler()); } }).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture f = b.bind(port).sync(); f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }
From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java
License:Open Source License
/** * Start the discovery process./*from w ww. j a va 2 s . c o m*/ * * @throws IOException on failure */ public void start() throws IOException { searchRequestRunnable = new SearchRequestRunnable(this); // set up the inbound channel handler bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(new DatagramToByteBufHandler()); // convert an incoming DatagramPacket into a ByteBuf pipeline.addLast(new OrderDecoder()); // convert an incoming ByteBuf into an Order pipeline.addLast(new InboundOrderHandler(listener)); // handle incoming Orders } }); // bind to the address ChannelFuture cf = bootstrap.bind(new InetSocketAddress(0)); cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { channel = (DatagramChannel) channelFuture.channel(); // perform initial search request group.execute(searchRequestRunnable); // schedule two quick follow-up search requests to make sure a camera didn't miss the first request group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS, TimeUnit.SECONDS); group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2, TimeUnit.SECONDS); // set up a recurring search request so we can keep track of cameras coming/going searchFuture = group.scheduleAtFixedRate(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2 + getSearchRequestFrequencySeconds, getSearchRequestFrequencySeconds, TimeUnit.SECONDS); } else { logger.error("Bind attempt failed", channelFuture.cause()); } } }); }
From source file:com.whizzosoftware.hobson.api.plugin.channel.AbstractChannelObjectPlugin.java
License:Open Source License
/** * Connect the channel.// w w w . j a v a 2 s. c o m * * @param b a Netty Bootstrap object */ synchronized private void connect(Bootstrap b) { logger.debug("connect()"); if (connectionState == State.NOT_CONNECTED) { logger.debug("Attempting to connect"); connectionState = State.CONNECTING; b.connect(socketAddress).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { logger.debug("Connection established"); connectionState = State.CONNECTED; // save the channel AbstractChannelObjectPlugin.this.channel = channelFuture.channel(); // set a close listener to notify the plugin subclass when the channel has closed channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { logger.info("Connection was closed"); channel = null; connectionState = State.NOT_CONNECTED; executeInEventLoop(new Runnable() { @Override public void run() { onChannelDisconnected(); } }); if (isRunning) { scheduleReconnect(channelFuture.channel().eventLoop()); } } }); executeInEventLoop(new Runnable() { @Override public void run() { onChannelConnected(); } }); } else { logger.warn("Connection attempt to " + socketAddress.toString() + " failed", channelFuture.cause()); connectionState = State.NOT_CONNECTED; if (isRunning) { scheduleReconnect(channelFuture.channel().eventLoop()); } } } }); } else { logger.debug("Ignoring connect request due to state: " + connectionState); } }
From source file:com.whizzosoftware.hobson.hub.websockets.WebSocketsPlugin.java
License:Open Source License
@Override public void onStartup(PropertyContainer config) { bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer(clientChannels, getAccessManager())); b.bind(PORT).addListener(new GenericFutureListener<ChannelFuture>() { @Override/*from ww w .j a v a 2 s.com*/ public void operationComplete(ChannelFuture future) throws Exception { WebSocketsPlugin.this.channel = future.channel(); logger.debug("WebSocket server started at port {}", PORT); getHubManager().getLocalManager().setWebSocketInfo("ws", PORT, null); } }); }