/** Triggered based on events from an {@link io.netty.handler.timeout.IdleStateHandler}. */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; // See class comment for timeout semantics. In addition to ensuring we only timeout while // there are outstanding requests, we also do a secondary consistency check to ensure // there's no race between the idle timeout and incrementing the numOutstandingRequests // (see SPARK-7003). // // To avoid a race between TransportClientFactory.createClient() and this code which could // result in an inactive client being returned, this needs to run in a synchronized block. synchronized (this) { boolean isActuallyOverdue = System.nanoTime() - responseHandler.getTimeOfLastRequestNs() > requestTimeoutNs; if (e.state() == IdleState.ALL_IDLE && isActuallyOverdue) { if (responseHandler.numOutstandingRequests() > 0) { String address = NettyUtils.getRemoteAddress(ctx.channel()); logger.error( "Connection to {} has been quiet for {} ms while there are outstanding " + "requests. Assuming connection is dead; please adjust spark.network.timeout if this " + "is wrong.", address, requestTimeoutNs / 1000 / 1000); client.timeOut(); ctx.close(); } else if (closeIdleConnections) { // While CloseIdleConnections is enable, we also close idle connection client.timeOut(); ctx.close(); } } } } ctx.fireUserEventTriggered(evt); }
private static void processGoAwayWriteResult( final ChannelHandlerContext ctx, final int lastStreamId, final long errorCode, final ByteBuf debugData, ChannelFuture future) { try { if (future.isSuccess()) { if (errorCode != NO_ERROR.code()) { if (logger.isDebugEnabled()) { logger.debug( format( "Sent GOAWAY: lastStreamId '%d', errorCode '%d', " + "debugData '%s'. Forcing shutdown of the connection.", lastStreamId, errorCode, debugData.toString(UTF_8)), future.cause()); } ctx.close(); } } else { if (logger.isErrorEnabled()) { logger.error( format( "Sending GOAWAY failed: lastStreamId '%d', errorCode '%d', " + "debugData '%s'. Forcing shutdown of the connection.", lastStreamId, errorCode, debugData.toString(UTF_8)), future.cause()); } ctx.close(); } } finally { // We're done with the debug data now. debugData.release(); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Channel incoming = ctx.channel(); System.out.println("Client:" + incoming.remoteAddress() + "异常"); cause.printStackTrace(); ctx.close(); }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ChannelPipeline p = ctx.pipeline(); SocksProtocolVersion version = SocksProtocolVersion.valueOf(in.readByte()); System.out.println(version); in.resetReaderIndex(); switch (version) { case SOCKS4a: p.addLast(new Socks4CmdRequestDecoder()); p.addLast(Socks4MessageEncoder.INSTANCE); break; case SOCKS5: p.addLast(new Socks5InitRequestDecoder()); p.addLast(Socks5MessageEncoder.INSTANCE); break; case UNKNOWN: in.clear(); ctx.close(); return; } p.addLast(SocksServerHandler.INSTANCE); p.remove(this); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("Channel Read"); if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.err.println("STATUS: " + response.getStatus()); System.err.println("VERSION: " + response.getProtocolVersion()); System.err.println(); if (!response.headers().isEmpty()) { for (String name : response.headers().names()) { for (String value : response.headers().getAll(name)) { System.err.println("HEADER: " + name + " = " + value); } } System.err.println(); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; System.err.print(content.content().toString(CharsetUtil.UTF_8)); System.err.flush(); if (content instanceof LastHttpContent) { System.err.println("} END OF CONTENT"); ctx.close(); } } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("================进入客户端InBoundHandler channelRead============"); // 如果是response if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; logger.debug( "客户端收到的响应CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE)); if (HttpHeaders.isContentLengthSet(response)) { reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response)); } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); reader.reading(content); content.release(); if (reader.isEnd()) { String resultStr = new String(reader.readFull()); logger.debug("收到的服务端的消息是:" + resultStr); ctx.close(); } } logger.debug("================出客户端InBoundHandler channelRead============"); }
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception { if (event.getClass() == QueueEvent.class) { // Initiate envelope processing, after the queue state has // changed from empty to non-empty. writeAndFlushNextEnvelopeIfPossible(); } else if (event.getClass() == IdleStateEvent.class) { // Channel idle => try to close boolean closeConnection = false; // Only close the connection, if there are no queued envelopes. We have // to ensure that there is no race between closing the channel and // enqueuing a new envelope. synchronized (channel) { if (queuedEnvelopes.isEmpty() && !hasRequestedClose) { hasRequestedClose = true; closeConnection = true; // Notify the connection manager that this channel has been // closed. connectionManager.close(receiver); } } if (closeConnection) { ctx.close().addListener(new ChannelCloseListener()); } } else { throw new IllegalStateException("Triggered unknown event."); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (LOG.isTraceEnabled()) { LOG.trace("Channel disconnect caused close:{}", cause); } ctx.close(); }
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { String response = msg.content().toString(CharsetUtil.UTF_8); if (response.startsWith("QOTM: ")) { System.out.println("Quote of the Moment: " + response.substring(6)); ctx.close(); } }
@Override public void exceptionCaught(ChannelHandlerContext remoteChannelCtx, Throwable cause) throws Exception { logger.error( cause.getMessage() + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), cause); remoteChannelCtx.close(); }
/** * 取代netty3.0中的channelDisconnected(),客户端主动关闭连接 * * @param ctx * @throws Exception */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.info("[" + ctx.channel().remoteAddress() + "] : is inactive......"); handlerDispatcher.removeChannelInfo(ctx.channel()); System.out.println("[" + ctx.channel().remoteAddress() + "] : is inactive......"); ctx.close(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (HttpServices.shouldLogException(cause)) { logger.warn(cause.getMessage(), cause); } ctx.close(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error("[" + ctx.channel().remoteAddress() + "] 出异常……"); // cause.printStackTrace(); handlerDispatcher.removeChannelInfo(ctx.channel()); ctx.close(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (ctx.channel().isActive()) { if (cause instanceof ReadTimeoutException) { ProxyServer.getInstance().getLogger().log(Level.WARNING, "{0} - read timed out", handler); } else if (cause instanceof BadPacketException) { ProxyServer.getInstance() .getLogger() .log(Level.WARNING, "{0} - bad packet ID, are mods in use!?", handler); } else if (cause instanceof IOException) { ProxyServer.getInstance() .getLogger() .log( Level.WARNING, "{0} - IOException: {1}", new Object[] {handler, cause.getMessage()}); } else { ProxyServer.getInstance() .getLogger() .log(Level.SEVERE, handler + " - encountered exception", cause); } if (handler != null) { try { handler.exception(cause); } catch (Exception ex) { ProxyServer.getInstance() .getLogger() .log(Level.SEVERE, handler + " - exception processing exception", ex); } } ctx.close(); } }
@Override public void channelReadComplete(ChannelHandlerContext ctx) { if (responseAssertProcessor != null) { this.responseAssertProcessor.process(responseContext, outgoingMessage); } ctx.close(); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof EchoFile) { EchoFile ef = (EchoFile) msg; int SumCountPackage = ef.getSumCountPackage(); int countPackage = ef.getCountPackage(); byte[] bytes = ef.getBytes(); String md5 = ef.getFile_md5(); // 文件名 String path = file_dir + File.separator + md5; File file = new File(path); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.seek(countPackage * dataLength - dataLength); randomAccessFile.write(bytes); LOGGER.debug("总包数:" + ef.getSumCountPackage()); LOGGER.debug("收到第" + countPackage + "包"); LOGGER.debug("本包字节数:" + bytes.length); countPackage = countPackage + 1; if (countPackage <= SumCountPackage) { ef.setCountPackage(countPackage); ctx.writeAndFlush(ef); randomAccessFile.close(); } else { randomAccessFile.close(); ctx.close(); } } }
/** Is called when a write timeout was detected */ protected void writeTimedOut(ChannelHandlerContext ctx) throws Exception { if (!closed) { ctx.fireExceptionCaught(WriteTimeoutException.INSTANCE); ctx.close(); closed = true; } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof TooLongFrameException) { ctx.close(); } else { super.exceptionCaught(ctx, cause); } }
// 暴力停止客户端,先执行exceptionCaught,接着执行channelInactive。 @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7) Channel incoming = ctx.channel(); System.out.println("SimpleChatClient:" + incoming.remoteAddress() + "异常"); // 当出现异常就关闭连接 cause.printStackTrace(); ctx.close(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.warn( "Exception in connection from " + NettyUtils.getRemoteAddress(ctx.channel()), cause); requestHandler.exceptionCaught(cause); responseHandler.exceptionCaught(cause); ctx.close(); }
public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) try { handleHttpRequest(ctx, (HttpRequest) msg); } catch (Exception e) { e.printStackTrace(); } ctx.close(); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof ConnectException) { startTime = -1; println("Failed to connect: " + cause.getMessage()); } cause.printStackTrace(); ctx.close(); }
@Override protected final void die(Throwable cause) { super.die(cause); if (ctx.channel().isOpen()) ctx.close(); // Ensure to release server references userActor = null; ctx = null; }
@Override public void exceptionCaught(ChannelHandlerContext context, Throwable cause) { if (cause instanceof IOException) { log.debug("IOException inside channel handling pipeline.", cause); } else { log.error("non-IOException inside channel handling pipeline.", cause); } context.close(); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("client channelRead.."); // 服务端返回消息后 Result result = (Result) ctx.channel().attr(RESULT).get(); result.set(msg); ctx.close(); System.out.println("Now is :" + msg); }
private void safeClose( final ChannelHandlerContext ctx, ChannelFuture flushFuture, final ChannelPromise promise) { if (!ctx.channel().isActive()) { ctx.close(promise); return; } final ScheduledFuture<?> timeoutFuture; if (closeNotifyTimeoutMillis > 0) { // Force-close the connection if close_notify is not fully sent in time. timeoutFuture = ctx.executor() .schedule( new Runnable() { @Override public void run() { logger.warn( "{} Last write attempt timed out; force-closing the connection.", ctx.channel()); // We notify the promise in the TryNotifyListener as there is a "race" where // the close(...) call // by the timeoutFuture and the close call in the flushFuture listener will be // called. Because of // this we need to use trySuccess() and tryFailure(...) as otherwise we can // cause an // IllegalStateException. ctx.close(ctx.newPromise()).addListener(new ChannelPromiseNotifier(promise)); } }, closeNotifyTimeoutMillis, TimeUnit.MILLISECONDS); } else { timeoutFuture = null; } // Close the connection if close_notify is sent in time. flushFuture.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture f) throws Exception { if (timeoutFuture != null) { timeoutFuture.cancel(false); } // Trigger the close in all cases to make sure the promise is notified // See https://github.com/netty/netty/issues/2358 // // We notify the promise in the ChannelPromiseNotifier as there is a "race" where the // close(...) call // by the timeoutFuture and the close call in the flushFuture listener will be called. // Because of // this we need to use trySuccess() and tryFailure(...) as otherwise we can cause an // IllegalStateException. ctx.close(ctx.newPromise()).addListener(new ChannelPromiseNotifier(promise)); } }); }
public synchronized void close() { try { LOG.info("Closing connection"); ctx.close().sync(); connected = false; } catch (Exception e) { LOG.error("Closing failed", e); } }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (!handshakeFuture.isDone()) { handshakeFuture.setFailure(cause); } for (WebSocketEventListener l : listensers) { l.onError(ctx, cause, response); } ctx.close(); }
void stopServer() { if (messageServerThread != null) { messageServerThread.stopServer(); messageServerThread = null; listenerQueue.onDestory(); } if (AuthChannelHandlerContext != null) { AuthChannelHandlerContext.close(); AuthChannelHandlerContext = null; } }
protected void decode(ChannelHandlerContext context, ByteBuf buffer) throws Exception { ChannelPipeline pipeline = context.pipeline(); if (detectSsl && SslHandler.isEncrypted(buffer)) { SSLEngine engine = SSL_SERVER_CONTEXT.getValue().createSSLEngine(); engine.setUseClientMode(false); pipeline.addLast( new SslHandler(engine), new ChunkedWriteHandler(), new PortUnificationServerHandler(delegatingHttpRequestHandler, false, detectGzip)); } else { int magic1 = buffer.getUnsignedByte(buffer.readerIndex()); int magic2 = buffer.getUnsignedByte(buffer.readerIndex() + 1); if (detectGzip && magic1 == 31 && magic2 == 139) { pipeline.addLast( new JZlibEncoder(ZlibWrapper.GZIP), new JdkZlibDecoder(ZlibWrapper.GZIP), new PortUnificationServerHandler(delegatingHttpRequestHandler, detectSsl, false)); } else if (isHttp(magic1, magic2)) { NettyUtil.initHttpHandlers(pipeline); pipeline.addLast(delegatingHttpRequestHandler); if (BuiltInServer.LOG.isDebugEnabled()) { pipeline.addLast( new ChannelOutboundHandlerAdapter() { @Override public void write( ChannelHandlerContext context, Object message, ChannelPromise promise) throws Exception { if (message instanceof HttpResponse) { // BuiltInServer.LOG.debug("OUT HTTP:\n" + message); HttpResponse response = (HttpResponse) message; BuiltInServer.LOG.debug( "OUT HTTP: " + response.getStatus().code() + " " + response.headers().get("Content-type")); } super.write(context, message, promise); } }); } } else if (magic1 == 'C' && magic2 == 'H') { buffer.skipBytes(2); pipeline.addLast(new CustomHandlerDelegator()); } else { BuiltInServer.LOG.warn("unknown request, first two bytes " + magic1 + " " + magic2); context.close(); } } // must be after new channels handlers addition (netty bug?) ensureThatExceptionHandlerIsLast(pipeline); pipeline.remove(this); context.fireChannelRead(buffer); }