本文整理汇总了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;
}
示例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");
}
}
示例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);
}
}
示例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);
}
示例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();
}
}
示例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());
}
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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");
}
}
示例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));
}
示例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);
}
}
示例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);
}