本文整理汇总了Java中org.jboss.netty.channel.ChannelFuture.addListener方法的典型用法代码示例。如果您正苦于以下问题:Java ChannelFuture.addListener方法的具体用法?Java ChannelFuture.addListener怎么用?Java ChannelFuture.addListener使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.jboss.netty.channel.ChannelFuture
的用法示例。
在下文中一共展示了ChannelFuture.addListener方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: 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);
}
}
示例2: 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);
}
示例3: 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);
}
示例4: 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);
//SECUREKEEPER: Enable ssl only if specified
//if (secure) {
if(encryption.equals("ssl")){
SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
ChannelFuture handshakeFuture = sslHandler.handshake();
handshakeFuture.addListener(new CertificateVerifier(sslHandler, cnxn));
} else {
allChannels.add(ctx.getChannel());
addCnxn(cnxn);
}
}
示例5: 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);
}
}
示例6: sendResponse
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
public void sendResponse(Throwable error) throws IOException {
byte type = 0;
type = TransportOption.setTypeMessage(type);
byte status = 0;
status = TransportOption.setErrorResponse(status);
CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry();
BytesStreamOutput stream = cachedEntry.bytes();
stream.skip(MessageProtocol.HEADER_SIZE);
StreamableThrowable streamableThrowable = new StreamableThrowable(error);
streamableThrowable.writeTo(stream);
stream.close();
ChannelBuffer buffer = stream.bytesReference().toChannelBuffer();
MessageProtocol.writeHeader(buffer, type, requestId, status);
ChannelFuture future = channel.write(buffer);
future.addListener(new TransportModule.CacheFutureListener(cachedEntry));
}
示例7: exceptionCaught
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
protected void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
if (!lifecycle.started()) {
// ignore
return;
}
if (isCloseConnectionException(e.getCause())) {
logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
// close the channel, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
} else if (isConnectException(e.getCause())) {
logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel());
// close the channel as safe measure, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
} else if (e.getCause() instanceof CancelledKeyException) {
logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
// close the channel as safe measure, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
} else if (e.getCause() instanceof SizeHeaderFrameDecoder.HttpOnTransportException) {
// in case we are able to return data, serialize the exception content and sent it back to the client
if (ctx.getChannel().isOpen()) {
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(e.getCause().getMessage().getBytes(Charsets.UTF_8));
ChannelFuture channelFuture = ctx.getChannel().write(buffer);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
future.getChannel().close();
}
});
}
} else {
logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel());
// close the channel, which will cause a node to be disconnected if relevant
ctx.getChannel().close();
disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
}
}
示例8: sendResponse
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
if (transport.compress) {
options = TransportResponseOptions.builder(options).withCompress(transport.compress).build();
}
byte status = 0;
status = TransportStatus.setResponse(status);
ReleasableBytesStreamOutput bStream = new ReleasableBytesStreamOutput(transport.bigArrays);
boolean addedReleaseListener = false;
try {
bStream.skip(NettyHeader.HEADER_SIZE);
StreamOutput stream = bStream;
if (options.compress()) {
status = TransportStatus.setCompress(status);
stream = CompressorFactory.defaultCompressor().streamOutput(stream);
}
stream.setVersion(version);
response.writeTo(stream);
stream.close();
ReleasablePagedBytesReference bytes = bStream.bytes();
ChannelBuffer buffer = bytes.toChannelBuffer();
NettyHeader.writeHeader(buffer, requestId, status, version);
ChannelFuture future = channel.write(buffer);
ReleaseChannelFutureListener listener = new ReleaseChannelFutureListener(bytes);
future.addListener(listener);
addedReleaseListener = true;
transportServiceAdapter.onResponseSent(requestId, action, response, options);
} finally {
if (!addedReleaseListener) {
Releasables.close(bStream.bytes());
}
}
}
示例9: sendMap
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
* Calls sendMapOutput for the mapId pointed by ReduceContext.mapsToSend
* and increments it. This method is first called by messageReceived()
* maxSessionOpenFiles times and then on the completion of every
* sendMapOutput operation. This limits the number of open files on a node,
* which can get really large(exhausting file descriptors on the NM) if all
* sendMapOutputs are called in one go, as was done previous to this change.
* @param reduceContext used to call sendMapOutput with correct params.
* @return the ChannelFuture of the sendMapOutput, can be null.
*/
public ChannelFuture sendMap(ReduceContext reduceContext)
throws Exception {
ChannelFuture nextMap = null;
if (reduceContext.getMapsToSend().get() <
reduceContext.getMapIds().size()) {
int nextIndex = reduceContext.getMapsToSend().getAndIncrement();
String mapId = reduceContext.getMapIds().get(nextIndex);
try {
MapOutputInfo info = reduceContext.getInfoMap().get(mapId);
if (info == null) {
info = getMapOutputInfo(reduceContext.getOutputBasePathStr() +
mapId, mapId, reduceContext.getReduceId(),
reduceContext.getUser());
}
nextMap = sendMapOutput(
reduceContext.getCtx(),
reduceContext.getCtx().getChannel(),
reduceContext.getUser(), mapId,
reduceContext.getReduceId(), info);
if (null == nextMap) {
sendError(reduceContext.getCtx(), NOT_FOUND);
return null;
}
nextMap.addListener(new ReduceMapFileCount(reduceContext));
} catch (IOException e) {
LOG.error("Shuffle error :", e);
String errorMessage = getErrorMessage(e);
sendError(reduceContext.getCtx(), errorMessage,
INTERNAL_SERVER_ERROR);
return null;
}
}
return nextMap;
}
示例10: openChannel
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
// blocking for channel to be done
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
}
// here we need to wait it in other thread
final CountDownLatch channelLatch = new CountDownLatch(1);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
channelLatch.countDown();
}
});
try {
channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
throw new CamelException("Interrupted while waiting for " + "connection to "
+ configuration.getAddress());
}
if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
if (channelFuture.getCause() != null) {
cause.initCause(channelFuture.getCause());
}
throw cause;
}
Channel answer = channelFuture.getChannel();
if (LOG.isDebugEnabled()) {
LOG.debug("Creating connector to address: {}", configuration.getAddress());
}
return answer;
}
示例11: writeToAgent
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
/**
* Write response back to agent
*
* @param e
* @param buffer
* @param agentSession
*/
private final void writeToAgent(MessageEvent e, ChannelBuffer buffer,
AgentSession agentSession) {
// write responses back to agent
ChannelFuture future = e.getChannel().write(buffer);
agentSession.setSentResponseRequest();
agentSession.setReleasedCoordinationLock();
// check slow writes:
if ((agentSession.getFileWriteEndTime() - agentSession
.getFileWriteStartTime()) > 500) {
LOG.error("File writing is slowing down please check the log directory");
}
if (future != null) {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
try {
ChannelFutureListener.CLOSE.operationComplete(f);
} catch (Throwable t) {
LOG.error("ERROR While closing channel :"
+ f.getChannel() + " " + f.getCause());
}
}
});
}
}
示例12: sendRequest
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
public void sendRequest(final RequestWrapper wrapper, final int timeout) throws Exception {
final long beginTime = System.currentTimeMillis();
final Client self = this;
ChannelFuture writeFuture = cf.getChannel().write(wrapper);
// use listener to avoid wait for write & thread context switch
writeFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
return;
}
String errorMsg = "";
// write timeout
if (System.currentTimeMillis() - beginTime >= timeout) {
errorMsg = "write to send buffer consume too long time(" + (System.currentTimeMillis() - beginTime) + "),request id is:"
+ wrapper.getId();
}
if (future.isCancelled()) {
errorMsg = "Send request to " + cf.getChannel().toString() + " cancelled by user,request id is:" + wrapper.getId();
}
if (!future.isSuccess()) {
if (cf.getChannel().isConnected()) {
// maybe some exception,so close the channel
cf.getChannel().close();
} else {
NettyClientFactory.getInstance().removeClient(key, self);
}
errorMsg = "Send request to " + cf.getChannel().toString() + " error" + future.getCause();
}
LOGGER.error(errorMsg);
ResponseWrapper response = new ResponseWrapper(wrapper.getId(), wrapper.getCodecType(), wrapper.getProtocolType());
response.setException(new Exception(errorMsg));
self.putResponse(response);
}
});
}
示例13: openChannel
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
// blocking for channel to be done
if (LOG.isTraceEnabled()) {
LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
}
// here we need to wait it in other thread
final CountDownLatch channelLatch = new CountDownLatch(1);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
channelLatch.countDown();
}
});
try {
channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
throw new CamelException("Interrupted while waiting for " + "connection to "
+ configuration.getAddress());
}
if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
if (channelFuture.getCause() != null) {
cause.initCause(channelFuture.getCause());
}
throw cause;
}
Channel answer = channelFuture.getChannel();
// to keep track of all channels in use
allChannels.add(answer);
if (LOG.isDebugEnabled()) {
LOG.debug("Creating connector to address: {}", configuration.getAddress());
}
return answer;
}
示例14: run
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
@SuppressWarnings("rawtypes")
public void run() {
// pipeline
if (message instanceof List) {
List messages = (List) message;
for (Object messageObject : messages) {
threadPool.execute(new HandlerRunnable(ctx, messageObject, threadPool));
}
} else {
RequestWrapper request = (RequestWrapper) message;
long beginTime = System.currentTimeMillis();
ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType()).handleRequest(request);
final int id = request.getId();
// already timeout,so not return
if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
LOGGER.warn("timeout,so give up send response to client,requestId is:" + id + ",client is:" + ctx.getChannel().getRemoteAddress()
+ ",consumetime is:" + (System.currentTimeMillis() - beginTime) + ",timeout is:" + request.getTimeout());
return;
}
ChannelFuture wf = ctx.getChannel().write(responseWrapper);
wf.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
LOGGER.error("server write response error,request id is: " + id);
}
}
});
}
}
示例15: sendRequest
import org.jboss.netty.channel.ChannelFuture; //导入方法依赖的package包/类
private void sendRequest(final StateMachine.Fsm fsm, RequestEvent request) {
TSOProto.Request req = request.getRequest();
if (req.hasTimestampRequest()) {
timestampRequests.add(new RequestAndTimeout(request, newTimeout(new TimestampRequestTimeoutEvent())));
} else if (req.hasCommitRequest()) {
TSOProto.CommitRequest commitReq = req.getCommitRequest();
commitRequests.put(commitReq.getStartTimestamp(), new RequestAndTimeout(
request, newTimeout(new CommitRequestTimeoutEvent(commitReq.getStartTimestamp()))));
} else if (req.hasFenceRequest()) {
TSOProto.FenceRequest fenceReq = req.getFenceRequest();
fenceRequests.put(fenceReq.getTableId(), new RequestAndTimeout(
request, newTimeout(new FenceRequestTimeoutEvent(fenceReq.getTableId()))));
} else {
request.error(new IllegalArgumentException("Unknown request type"));
return;
}
ChannelFuture f = channel.write(req);
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
fsm.sendEvent(new ErrorEvent(future.getCause()));
}
}
});
}