當前位置: 首頁>>代碼示例>>Java>>正文


Java ChannelFuture類代碼示例

本文整理匯總了Java中org.jboss.netty.channel.ChannelFuture的典型用法代碼示例。如果您正苦於以下問題:Java ChannelFuture類的具體用法?Java ChannelFuture怎麽用?Java ChannelFuture使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ChannelFuture類屬於org.jboss.netty.channel包,在下文中一共展示了ChannelFuture類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: send

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
/**
 * Sends this response to all the passed channels as a {@link TextWebSocketFrame}
 * @param listener A channel future listener to attach to each channel future. Ignored if null.
 * @param channels The channels to send this response to
 * @return An array of the futures for the write of this response to each channel written to
 */
public ChannelFuture[] send(ChannelFutureListener listener, Channel...channels) {
	if(channels!=null && channels.length>0) {
		Set<ChannelFuture> futures = new HashSet<ChannelFuture>(channels.length);
		if(opCode==null) {
			opCode = "ok";
		}
		TextWebSocketFrame frame = new TextWebSocketFrame(this.toChannelBuffer());
		for(Channel channel: channels) {
			if(channel!=null && channel.isWritable()) {
				ChannelFuture cf = Channels.future(channel);
				if(listener!=null) cf.addListener(listener);
				channel.getPipeline().sendDownstream(new DownstreamMessageEvent(channel, cf, frame, channel.getRemoteAddress()));
				futures.add(cf);
			}
		}
		return futures.toArray(new ChannelFuture[futures.size()]);
	}		
	return EMPTY_CHANNEL_FUTURE_ARR;
}
 
開發者ID:nickman,項目名稱:HeliosStreams,代碼行數:26,代碼來源:Netty3JSONResponse.java

示例2: send

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
public void send(Object message, boolean sent) throws RemotingException {
    super.send(message, sent);
    
    boolean success = true;
    int timeout = 0;
    try {
        ChannelFuture future = channel.write(message);
        if (sent) {
            timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
            success = future.await(timeout);
        }
        Throwable cause = future.getCause();
        if (cause != null) {
            throw cause;
        }
    } catch (Throwable e) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e);
    }
    
    if(! success) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + "in timeout(" + timeout + "ms) limit");
    }
}
 
開發者ID:dachengxi,項目名稱:EatDubbo,代碼行數:25,代碼來源:NettyChannel.java

示例3: channelConnected

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
@Override
public void channelConnected(ChannelHandlerContext ctx,
        ChannelStateEvent e) throws Exception
{
    if (LOG.isTraceEnabled()) {
        LOG.trace("Channel connected " + e);
    }

    NettyServerCnxn cnxn = new NettyServerCnxn(ctx.getChannel(),
            zkServer, NettyServerCnxnFactory.this);
    ctx.setAttachment(cnxn);

    if (secure) {
        SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
        ChannelFuture handshakeFuture = sslHandler.handshake();
        handshakeFuture.addListener(new CertificateVerifier(sslHandler, cnxn));
    } else {
        allChannels.add(ctx.getChannel());
        addCnxn(cnxn);
    }
}
 
開發者ID:didichuxing2,項目名稱:https-github.com-apache-zookeeper,代碼行數:22,代碼來源:NettyServerCnxnFactory.java

示例4: testShuffleMetrics

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
/**
 * Validate shuffle connection and input/output metrics.
 *
 * @throws Exception exception
 */
@Test (timeout = 10000)
public void testShuffleMetrics() throws Exception {
  MetricsSystem ms = new MetricsSystemImpl();
  ShuffleHandler sh = new ShuffleHandler(ms);
  ChannelFuture cf = make(stub(ChannelFuture.class).
      returning(true, false).from.isSuccess());

  sh.metrics.shuffleConnections.incr();
  sh.metrics.shuffleOutputBytes.incr(1*MiB);
  sh.metrics.shuffleConnections.incr();
  sh.metrics.shuffleOutputBytes.incr(2*MiB);

  checkShuffleMetrics(ms, 3*MiB, 0 , 0, 2);

  sh.metrics.operationComplete(cf);
  sh.metrics.operationComplete(cf);

  checkShuffleMetrics(ms, 3*MiB, 1, 1, 0);
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:25,代碼來源:TestShuffleHandler.java

示例5: run

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
public void run() {
  // Configure the client.
  ChannelFactory factory = new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
  ClientBootstrap bootstrap = new ClientBootstrap(factory);

  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(setPipelineFactory());

  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);

  // Start the connection attempt.
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

  if (oneShot) {
    // Wait until the connection is closed or the connection attempt fails.
    future.getChannel().getCloseFuture().awaitUninterruptibly();

    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
  }
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:24,代碼來源:SimpleTcpClient.java

示例6: operationComplete

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
    if (!cf.isSuccess()) {
        synchronized (connections) {
            NodeConnection c = connections.remove(node.getNodeId());
            if (c != null) c.nuke();
            cf.getChannel().close();
        }
        
        String message = "[unknown error]";
        if (cf.isCancelled()) message = "Timed out on connect";
        if (cf.getCause() != null) message = cf.getCause().getMessage();
        logger.debug("[{}->{}] Could not connect to RPC " +
                     "node: {}", 
                     new Object[]{syncManager.getLocalNodeId(), 
                                  node.getNodeId(), 
                                  message});
    } else {
        logger.trace("[{}->{}] Channel future successful", 
                     syncManager.getLocalNodeId(), 
                     node.getNodeId());
    }
}
 
開發者ID:nsg-ethz,項目名稱:iTAP-controller,代碼行數:24,代碼來源:RPCService.java

示例7: bootstrap

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
public boolean bootstrap(HostAndPort seed, 
                         Node localNode) throws SyncException {
    this.localNode = localNode;
    succeeded = false;
    SocketAddress sa =
            new InetSocketAddress(seed.getHostText(), seed.getPort());
    ChannelFuture future = bootstrap.connect(sa);
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        logger.debug("Could not connect to " + seed, future.getCause());
        return false;
    }
    Channel channel = future.getChannel();
    logger.debug("[{}] Connected to {}", 
                 localNode != null ? localNode.getNodeId() : null,
                 seed);
    
    try {
        channel.getCloseFuture().await();
    } catch (InterruptedException e) {
        logger.debug("Interrupted while waiting for bootstrap");
        return succeeded;
    }
    return succeeded;
}
 
開發者ID:nsg-ethz,項目名稱:iTAP-controller,代碼行數:26,代碼來源:Bootstrap.java

示例8: connect

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
protected boolean connect(String hostname, int port) {
    ready = false;
    if (channel == null || !channel.isConnected()) {
        SocketAddress sa =
                new InetSocketAddress(hostname, port);
        ChannelFuture future = clientBootstrap.connect(sa);
        future.awaitUninterruptibly();
        if (!future.isSuccess()) {
            logger.error("Could not connect to " + hostname + 
                         ":" + port, future.getCause());
            return false;
        }
        channel = future.getChannel();
    }
    while (!ready && channel != null && channel.isConnected()) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) { }
    }
    if (!ready || channel == null || !channel.isConnected()) {
        logger.warn("Timed out connecting to {}:{}", hostname, port);
        return false;
    }
    logger.debug("Connected to {}:{}", hostname, port);
    return true;
}
 
開發者ID:nsg-ethz,項目名稱:iTAP-controller,代碼行數:27,代碼來源:RemoteSyncManager.java

示例9: createMockChannelFuture

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
public ChannelFuture createMockChannelFuture(Channel mockCh,
    final List<ShuffleHandler.ReduceMapFileCount> listenerList) {
  final ChannelFuture mockFuture = Mockito.mock(ChannelFuture.class);
  Mockito.when(mockFuture.getChannel()).thenReturn(mockCh);
  Mockito.doReturn(true).when(mockFuture).isSuccess();
  Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      //Add ReduceMapFileCount listener to a list
      if (invocation.getArguments()[0].getClass() ==
          ShuffleHandler.ReduceMapFileCount.class)
        listenerList.add((ShuffleHandler.ReduceMapFileCount)
            invocation.getArguments()[0]);
      return null;
    }
  }).when(mockFuture).addListener(Mockito.any(
      ShuffleHandler.ReduceMapFileCount.class));
  return mockFuture;
}
 
開發者ID:aliyun-beta,項目名稱:aliyun-oss-hadoop-fs,代碼行數:20,代碼來源:TestShuffleHandler.java

示例10: messageReceived

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	super.messageReceived(ctx, e);

	System.out.println("-------- Server  Channel messageRecieved "
			+ System.currentTimeMillis());

	if (induceError.get()) {
		System.out
				.println("Inducing Error in Server messageReceived method");
		throw new IOException("Induced error ");
	}

	MessageEventBag bag = new MessageEventBag();
	bag.setBytes(e);
	bagList.add(bag);

	ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
	buffer.writeInt(200);

	ChannelFuture future = e.getChannel().write(buffer);

	future.addListener(ChannelFutureListener.CLOSE);

}
 
開發者ID:gerritjvv,項目名稱:bigstreams,代碼行數:27,代碼來源:ServerUtil.java

示例11: exceptionCaught

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
		throws Exception {
	System.out.println("Server Exception Caught");
	e.getCause().printStackTrace();

	/**
	 * Very important to respond here.
	 * The agent will always be listening for some kind of feedback.
	 */
	ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
	buffer.writeInt(500);

	ChannelFuture future = e.getChannel().write(buffer);

	future.addListener(ChannelFutureListener.CLOSE);

}
 
開發者ID:gerritjvv,項目名稱:bigstreams,代碼行數:19,代碼來源:ServerUtil.java

示例12: send

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
public void send(Object message, boolean sent) throws RemotingException {
    super.send(message, sent);
    
    boolean success = true;
    int timeout = 0;
    try {
        ChannelFuture future = channel.write(message);
        //FIXME  sent為true的話   要等待數據寫完才返回,失敗拋出異常   add by jileng
        if (sent) {
            timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
            // 寫超時了,難道不能取消這次寫操作?
            success = future.await(timeout);
        }
        Throwable cause = future.getCause();
        if (cause != null) {
            throw cause;
        }
    } catch (Throwable e) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e);
    }
    
    if(! success) {
        throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
                + "in timeout(" + timeout + "ms) limit");
    }
}
 
開發者ID:spccold,項目名稱:dubbo-comments,代碼行數:27,代碼來源:NettyChannel.java

示例13: sendResponse

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
public void sendResponse(Object obj) throws IOException {
	byte type = 0;
	type = TransportOption.setTypeMessage(type);
	byte status = 0;
	status = TransportOption.setResponse(status);
	status = TransportOption.setResponseObject(status);
	byte resType = 0;
	resType = TransportOption.setResponseObject(resType);
    CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry();
    BytesStreamOutput stream = cachedEntry.bytes();
    stream.skip(MessageProtocol.HEADER_SIZE);
    stream.writeGenericValue(obj);
    stream.close();
    
    ChannelBuffer buffer = stream.bytesReference().toChannelBuffer();
    MessageProtocol.writeHeader(buffer, type, requestId, status);
    ChannelFuture future = channel.write(buffer);
    future.addListener(new TransportModule.CacheFutureListener(cachedEntry));
}
 
開發者ID:gncloud,項目名稱:fastcatsearch3,代碼行數:20,代碼來源:TransportChannel.java

示例14: writeBodyAsync

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
/**
 * Writes the given body to Netty channel. Will <b>not</b >wait until the body has been written.
 *
 * @param log             logger to use
 * @param channel         the Netty channel
 * @param remoteAddress   the remote address when using UDP
 * @param body            the body to write (send)
 * @param exchange        the exchange
 * @param listener        listener with work to be executed when the operation is complete
 */
public static void writeBodyAsync(Logger log, Channel channel, SocketAddress remoteAddress, Object body,
                                  Exchange exchange, ChannelFutureListener listener) {
    ChannelFuture future;
    if (remoteAddress != null) {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} remote address: {} writing body: {}", new Object[]{channel, remoteAddress, body});
        }
        future = channel.write(body, remoteAddress);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Channel: {} writing body: {}", new Object[]{channel, body});
        }
        future = channel.write(body);
    }

    if (listener != null) {
        future.addListener(listener);
    }
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:30,代碼來源:NettyHelper.java

示例15: write

import org.jboss.netty.channel.ChannelFuture; //導入依賴的package包/類
/**
 * {@inheritDoc}
 * @see org.jboss.netty.channel.Channel#write(java.lang.Object)
 */
@Override
public ChannelFuture write(Object message) {
	if(message!=null) {
		if(message instanceof FileRegion) {
			try {
				Pipe pipe = Pipe.open();
				FileRegion fr = (FileRegion)message;
				
				long bytesToRead = fr.getCount();
				fr.transferTo(pipe.sink(), 0L);
				byte[] content = new byte[(int)bytesToRead];
				pipe.source().read(ByteBuffer.wrap(content));
				channelWrites.add(content);
			} catch (Exception ex) {
				log.error("Failed to read content from pipe", ex);
				channelWrites.add(ex);
			}
		} else {
			channelWrites.add(message);
		}
		log.info("Received Channel Write [{}]  type:[{}]", message, message.getClass().getName());
	}
	
	return Channels.succeededFuture(this);
}
 
開發者ID:nickman,項目名稱:HeliosStreams,代碼行數:30,代碼來源:InvocationChannel.java


注:本文中的org.jboss.netty.channel.ChannelFuture類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。