List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.newlandframework.avatarmq.broker.server.AvatarMQBrokerServer.java
License:Apache License
public void start() { try {//www .java 2 s. co m String ipAddress = NettyUtil.socketAddress2String(serverIpAddr); System.out.printf("broker server ip:[%s]\n", ipAddress); ChannelFuture sync = this.bootstrap.bind().sync(); super.start(); sync.channel().closeFuture().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); brokerServerPort = addr.getPort(); } catch (InterruptedException ex) { Logger.getLogger(AvatarMQBrokerServer.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.newlandframework.avatarmq.netty.MessageConnectFactory.java
License:Apache License
public void connect() { Preconditions.checkNotNull(messageHandler, "Message's Handler is Null!"); try {/*www. ja va 2 s . c om*/ init(); ChannelFuture channelFuture = bootstrap.connect(this.remoteAddr).sync(); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { Channel channel = future.channel(); messageChannel = channel; } }); System.out.println("ip address:" + this.remoteAddr.toString()); connected = true; } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.newlandframework.rpc.netty.MessageRecvExecutor.java
License:Apache License
public void start() { try {/*from w ww.j a va2s . c o m*/ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker).channel(NioServerSocketChannel.class) .childHandler(new MessageRecvChannelInitializer(handlerMap) .buildRpcSerializeProtocol(serializeProtocol)) .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); String[] ipAddr = serverAddress.split(MessageRecvExecutor.DELIMITER); if (ipAddr.length == 2) { String host = ipAddr[0]; int port = Integer.parseInt(ipAddr[1]); ChannelFuture future = null; future = bootstrap.bind(host, port).sync(); System.out.printf( "[author tangjie] Netty RPC Server start success!\nip:%s\nport:%d\nprotocol:%s\n\n", host, port, serializeProtocol); future.channel().closeFuture().sync(); } else { System.out.printf("[author tangjie] Netty RPC Server start fail!\n"); } } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.newlandframework.rpc.netty.MessageSendInitializeTask.java
License:Apache License
public Boolean call() { Bootstrap b = new Bootstrap(); b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true); b.handler(new MessageSendChannelInitializer().buildRpcSerializeProtocol(protocol)); ChannelFuture channelFuture = b.connect(serverAddress); channelFuture.addListener(new ChannelFutureListener() { public void operationComplete(final ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class); RpcServerLoader.getInstance().setMessageSendHandler(handler); }/*from ww w .j a va 2s.c o m*/ } }); return Boolean.TRUE; }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private <T> ListenableFuture<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f, boolean useCache, boolean asyncConnect, boolean reclaimCache) throws IOException { if (isClose.get()) { throw new IOException("Closed"); }//w w w . ja va2s . c o m if (request.getUrl().startsWith(WEBSOCKET) && !validateWebSocketRequest(request, asyncHandler)) { throw new IOException("WebSocket method must be a GET"); } ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request); boolean useProxy = proxyServer != null; URI uri; if (useRawUrl) { uri = request.getRawURI(); } else { uri = request.getURI(); } Channel channel = null; if (useCache) { if (f != null && f.reuseChannel() && f.channel() != null) { channel = f.channel(); } else { URI connectionKeyUri = useProxy ? proxyServer.getURI() : uri; channel = lookupInCache(connectionKeyUri, request.getConnectionPoolKeyStrategy()); } } ByteBuf bufferedBytes = null; if (f != null && f.getRequest().getFile() == null && !f.getNettyRequest().getMethod().name().equals(HttpMethod.CONNECT.name())) { bufferedBytes = f.getNettyRequest().data(); } boolean useSSl = isSecure(uri) && !useProxy; if (channel != null && channel.isOpen() && channel.isActive()) { HttpRequest nettyRequest = buildRequest(config, request, uri, f == null ? false : f.isConnectAllowed(), bufferedBytes, proxyServer); if (f == null) { f = newFuture(uri, request, asyncHandler, nettyRequest, config, this, proxyServer); } else { nettyRequest = buildRequest(config, request, uri, f.isConnectAllowed(), bufferedBytes, proxyServer); f.setNettyRequest(nettyRequest); } f.setState(NettyResponseFuture.STATE.POOLED); f.attachChannel(channel, false); log.debug("\nUsing cached Channel {}\n for request \n{}\n", channel, nettyRequest); channel.pipeline().context(NettyAsyncHttpProvider.class).attr(DEFAULT_ATTRIBUTE).set(f); try { writeRequest(channel, config, f, nettyRequest); } catch (Exception ex) { log.debug("writeRequest failure", ex); if (useSSl && ex.getMessage() != null && ex.getMessage().contains("SSLEngine")) { log.debug("SSLEngine failure", ex); f = null; } else { try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("doConnect.writeRequest()", t); } IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } } return f; } // Do not throw an exception when we need an extra connection for a redirect. if (!reclaimCache && !connectionsPool.canCacheConnection()) { IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections()); try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("!connectionsPool.canCacheConnection()", t); } throw ex; } boolean acquiredConnection = false; if (trackConnections) { if (!reclaimCache) { if (!freeConnections.tryAcquire()) { IOException ex = new IOException("Too many connections " + config.getMaxTotalConnections()); try { asyncHandler.onThrowable(ex); } catch (Throwable t) { log.warn("!connectionsPool.canCacheConnection()", t); } throw ex; } else { acquiredConnection = true; } } } NettyConnectListener<T> c = new NettyConnectListener.Builder<T>(config, request, asyncHandler, f, this, bufferedBytes).build(uri); boolean avoidProxy = ProxyUtils.avoidProxy(proxyServer, uri.getHost()); if (useSSl) { constructSSLPipeline(c); } ChannelFuture channelFuture; Bootstrap bootstrap = request.getUrl().startsWith(WEBSOCKET) ? (useSSl ? secureWebSocketBootstrap : webSocketBootstrap) : (useSSl ? secureBootstrap : plainBootstrap); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeoutInMs()); try { InetSocketAddress remoteAddress; if (request.getInetAddress() != null) { remoteAddress = new InetSocketAddress(request.getInetAddress(), AsyncHttpProviderUtils.getPort(uri)); } else if (proxyServer == null || avoidProxy) { remoteAddress = new InetSocketAddress(AsyncHttpProviderUtils.getHost(uri), AsyncHttpProviderUtils.getPort(uri)); } else { remoteAddress = new InetSocketAddress(proxyServer.getHost(), proxyServer.getPort()); } if (request.getLocalAddress() != null) { channelFuture = bootstrap.connect(remoteAddress, new InetSocketAddress(request.getLocalAddress(), 0)); } else { channelFuture = bootstrap.connect(remoteAddress); } } catch (Throwable t) { if (acquiredConnection) { freeConnections.release(); } abort(c.future(), t.getCause() == null ? t : t.getCause()); return c.future(); } boolean directInvokation = true; if (IN_IO_THREAD.get() && DefaultChannelFuture.isUseDeadLockChecker()) { directInvokation = false; } if (directInvokation && !asyncConnect && request.getFile() == null) { int timeOut = config.getConnectionTimeoutInMs() > 0 ? config.getConnectionTimeoutInMs() : Integer.MAX_VALUE; if (!channelFuture.awaitUninterruptibly(timeOut, TimeUnit.MILLISECONDS)) { if (acquiredConnection) { freeConnections.release(); } channelFuture.cancel(); abort(c.future(), new ConnectException(String.format("Connect operation to %s timeout %s", uri, timeOut))); } try { c.operationComplete(channelFuture); } catch (Exception e) { if (acquiredConnection) { freeConnections.release(); } IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); try { asyncHandler.onThrowable(ioe); } catch (Throwable t) { log.warn("c.operationComplete()", t); } throw ioe; } } else { channelFuture.addListener(c); } log.debug("\nNon cached request \n{}\n\nusing Channel \n{}\n", c.future().getNettyRequest(), channelFuture.getChannel()); if (!c.future().isCancelled() || !c.future().isDone()) { openChannels.add(channelFuture.channel()); c.future().attachChannel(channelFuture.channel(), false); } return c.future(); }
From source file:com.ning.http.client.providers.netty_4.NettyConnectListener.java
License:Apache License
public final void operationComplete(ChannelFuture f) throws Exception { if (f.isSuccess()) { Channel channel = f.channel(); channel.pipeline().context(NettyAsyncHttpProvider.class).attr(NettyAsyncHttpProvider.DEFAULT_ATTRIBUTE) .set(future);/* ww w.j a va2s. c om*/ SslHandler sslHandler = (SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER); if (!handshakeDone.getAndSet(true) && (sslHandler != null)) { ((SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER)).handshake() .addListener(this); return; } HostnameVerifier v = config.getHostnameVerifier(); if (sslHandler != null) { if (!v.verify(future.getURI().getHost(), sslHandler.engine().getSession())) { ConnectException exception = new ConnectException("HostnameVerifier exception."); future.abort(exception); throw exception; } } future.provider().writeRequest(f.channel(), config, future, nettyRequest); } else { Throwable cause = f.cause(); logger.debug("Trying to recover a dead cached channel {} with a retry value of {} ", f.channel(), future.canRetry()); if (future.canRetry() && cause != null && (NettyAsyncHttpProvider.abortOnDisconnectException(cause) || ClosedChannelException.class.isAssignableFrom(cause.getClass()) || future.getState() != NettyResponseFuture.STATE.NEW)) { logger.debug("Retrying {} ", nettyRequest); if (future.provider().remotelyClosed(f.channel(), future)) { return; } } logger.debug("Failed to recover from exception: {} with channel {}", cause, f.channel()); boolean printCause = f.cause() != null && cause.getMessage() != null; ConnectException e = new ConnectException( printCause ? cause.getMessage() + " to " + future.getURI().toString() : future.getURI().toString()); if (cause != null) { e.initCause(cause); } future.abort(e); } }
From source file:com.norming.netty.util.OIOUtil.java
/** * // w ww.j a v a 2 s . co m * ?Server * @param adapter * @return */ public static Object doConnect(final Netty4ClientAdapter adapter) { Object ret = null; EventLoopGroup workerGroup = new NioEventLoopGroup(1); Bootstrap bootstrap = new Bootstrap(); try { bootstrap.group(workerGroup).channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(adapter.getHost(), adapter.getPort())) .handler(new Netty4FactorialClientInitializer(adapter)).option(ChannelOption.TCP_NODELAY, true); ChannelFuture future = bootstrap.connect().sync(); future.channel().closeFuture().sync(); long s = System.currentTimeMillis(); while (System.currentTimeMillis() - s <= 1000 * 30) { if (adapter.isReceive()) { ret = adapter.getMsg(); break; } } } catch (Exception e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); } return ret; }
From source file:com.norming.netty.util.OIOUtil.java
/** * //from w ww . j av a2 s. co m * ?Server * @param adapter * @return */ public static void doConnect2(final Netty4ClientAdapter adapter) { EventLoopGroup workerGroup = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); try { bootstrap.group(workerGroup).channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(adapter.getHost(), adapter.getPort())) .handler(new Netty4FactorialClientInitializer(adapter)); ChannelFuture future = bootstrap.connect().sync(); future.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { workerGroup.shutdownGracefully(); } }
From source file:com.nus.mazegame.client.GameClient.java
public static void init(String host, final int port, final String type, SocketAddress localAddr) throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override//from w w w .ja v a2 s . co m protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // Decoders p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); p.addLast("bytesDecoder", new ByteArrayDecoder()); // Encoder p.addLast("frameEncoder", new LengthFieldPrepender(4)); p.addLast("bytesEncoder", new ByteArrayEncoder()); p.addLast(GameClientHandler.instance); GameInfo.instance.setType(type); GameInfo.instance.setHostPort(port); } }); // Make the connection attempt. SocketAddress address = new InetSocketAddress(host, port); ChannelFuture f; if (localAddr == null) f = b.connect(address).sync(); else f = b.connect(address, localAddr).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); }
From source file:com.nus.mazegame.server.GameServer.java
public static void init(int port, int x, int y, int treasure, boolean isSlave) throws Exception { GameService.gameService = new GameService(x, y, treasure, isSlave); // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//w ww.j a v a2s .co m ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // Decoders p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); p.addLast("bytesDecoder", new ByteArrayDecoder()); // Encoder p.addLast("frameEncoder", new LengthFieldPrepender(4)); p.addLast("bytesEncoder", new ByteArrayEncoder()); // p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new GameServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(port).sync(); Logger.getLogger(GameServerHandler.class.getName()).log(Level.INFO, "Server started..."); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }