Java Code Examples for io.netty.channel.ChannelHandlerContext#close()

The following examples show how to use io.netty.channel.ChannelHandlerContext#close() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
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("{} Sent GOAWAY: lastStreamId '{}', errorCode '{}', " +
                                 "debugData '{}'. Forcing shutdown of the connection.",
                                 ctx.channel(), lastStreamId, errorCode, debugData.toString(UTF_8), future.cause());
                }
                ctx.close();
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("{} Sending GOAWAY failed: lastStreamId '{}', errorCode '{}', " +
                             "debugData '{}'. Forcing shutdown of the connection.",
                             ctx.channel(), lastStreamId, errorCode, debugData.toString(UTF_8), future.cause());
            }
            ctx.close();
        }
    } finally {
        // We're done with the debug data now.
        debugData.release();
    }
}
 
Example 2
Source Project: redant   File: BadClientSilencer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
    ctx.close();

    // To clarify where exceptions are from, imports are not used
    if (e instanceof java.io.IOException                            ||  // Connection reset by peer, Broken pipe
        e instanceof java.nio.channels.ClosedChannelException       ||
        e instanceof io.netty.handler.codec.DecoderException        ||
        e instanceof io.netty.handler.codec.CorruptedFrameException ||  // Bad WebSocket frame
        e instanceof IllegalArgumentException             ||  // Use https://... to connect to HTTP server
        e instanceof javax.net.ssl.SSLException                     ||  // Use http://... to connect to HTTPS server
        e instanceof io.netty.handler.ssl.NotSslRecordException) {
        onBadClient(e);  // Maybe client is bad
    } else {
        onBadServer(e);  // Maybe server is bad
    }
}
 
Example 3
/**
 * Propagate failures to all buffered writes.
 */
@SuppressWarnings("FutureReturnValueIgnored")
protected final void fail(ChannelHandlerContext ctx, Throwable cause) {
  if (failCause == null) {
    failCause = cause;
  }
  if (bufferedWrites != null) {
    while (!bufferedWrites.isEmpty()) {
      ChannelWrite write = bufferedWrites.poll();
      write.promise.setFailure(cause);
      ReferenceCountUtil.release(write.msg);
    }
    bufferedWrites = null;
  }

  // In case something goes wrong ensure that the channel gets closed as the
  // NettyClientTransport relies on the channel's close future to get completed.
  ctx.close();
}
 
Example 4
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
                            Throwable cause) throws Exception {
    if (logger.isWarnEnabled()) {
        logger.warn("Unexpected exception from the server side", cause);
    }

    exception.compareAndSet(null, cause);
    ctx.close();
}
 
Example 5
Source Project: pulsar   File: ProxyConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    super.channelRegistered(ctx);
    ProxyService.activeConnections.inc();
    if (ProxyService.activeConnections.get() > service.getConfiguration().getMaxConcurrentInboundConnections()) {
        ctx.close();
        ProxyService.rejectedConnections.inc();
        return;
    }
}
 
Example 6
Source Project: fastjgame   File: NetUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 安静的关闭ctx,不产生任何影响
 */
public static void closeQuietly(@Nullable ChannelHandlerContext ctx) {
    if (null != ctx) {
        try {
            ctx.close();
        } catch (Throwable ignore) {

        }
    }
}
 
Example 7
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    boolean channelInUse = getAttribute(ctx.channel(), ChannelAttributeKey.IN_USE).orElse(false);

    if (channelInUse) {
        ctx.fireExceptionCaught(cause);
    } else {
        ctx.close();

        Optional<CompletableFuture<Void>> executeFuture = getAttribute(ctx.channel(), ChannelAttributeKey.EXECUTE_FUTURE_KEY);

        if (executeFuture.isPresent() && !executeFuture.get().isDone()) {
            log.error(() -> "An exception occurred on an channel (" + ctx.channel().id() + ") that was not in use, " +
                            "but was associated with a future that wasn't completed. This indicates a bug in the " +
                            "Java SDK, where a future was not completed while the channel was in use. The channel has " +
                            "been closed, and the future will be completed to prevent any ongoing issues.", cause);
            executeFuture.get().completeExceptionally(cause);
        } else if (isNettyIoException(cause) || hasNettyIoExceptionCause(cause)) {
            log.debug(() -> "An I/O exception (" + cause.getMessage() + ") occurred on a channel (" + ctx.channel().id() +
                            ") that was not in use. The channel has been closed. This is usually normal.");

        } else {
            log.warn(() -> "A non-I/O exception occurred on a channel (" + ctx.channel().id() + ") that was not in use. " +
                           "The channel has been closed to prevent any ongoing issues.", cause);
        }
    }
}
 
Example 8
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
	 ctx.flush();
     
     //close the connection after flushing data to client
	 if(close){
		 ctx.close();	 
	 }         
}
 
Example 9
Source Project: netty-custom-protocol   File: ServerHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
	System.err.println("--------服务器数据读异常----------: ");
	cause.printStackTrace();
    ctx.close();
}
 
Example 10
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    try {
        randomAccessFile.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ctx.close();
}
 
Example 11
Source Project: dfactor   File: DFHttpCliHandler.java    License: MIT License 4 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	cause.printStackTrace();
	ctx.close();
}
 
Example 12
@Override
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
    ctx.close(promise);
}
 
Example 13
Source Project: netty.book.kor   File: EchoClientHandler.java    License: MIT License 4 votes vote down vote up
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
    ctx.close();
}
 
Example 14
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    cause.printStackTrace();
    ctx.close();
}
 
Example 15
Source Project: garmadon   File: GreetingHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    PrometheusHttpMetrics.GREETINGS_IN_ERROR.inc();
    LOGGER.error("", cause);
    ctx.close();
}
 
Example 16
Source Project: ethereumj   File: EthHandler.java    License: MIT License 4 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    logger.error(cause.getCause().toString());
    super.exceptionCaught(ctx, cause);
    ctx.close();
}
 
Example 17
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    log.error("发生错误.......",cause);
    ctx.close();
}
 
Example 18
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if (exception.compareAndSet(null, cause)) {
        ctx.close();
    }
}
 
Example 19
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
}
 
Example 20
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
		List<Object> out) throws Exception {
	if (in.readableBytes() < RemotingConstants.THREE) {
		return;
	}
	final int magic1 = in.getUnsignedByte(in.readerIndex());
	final int magic2 = in.getUnsignedByte(in.readerIndex()+1);
	final int magic3 = in.getUnsignedByte(in.readerIndex()+2);
	if (isJar(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarReceiveHandler(ctx);
	} else if (isJas(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarSendHandler(ctx);
	} else if (isTxr(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesReceiveHandler(ctx);
	} else if (isTxs(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesSendHandler(ctx);
	} else if (isCmd(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndForgetCommandHandler(ctx);
	} else if(isCma(magic1, magic2, magic3)){
		throwAwayReadUnsignedBytes(in);
		invokeAsyncFireAndForgetCommandHandler(ctx);
	}/*else if (isCmg(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndGetCommandHandler(ctx);
	}*/ else if (isCmo(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndGetObjectResponseCommandHandler(ctx);
	} else if (isCmoHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndGetObjectResponseCommandHandlerForHA(ctx);
	} else if (isCmdHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeFireAndForgetCommandHandlerForHA(ctx);
	} else if (isTxrHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesReceiveHandlerForHA(ctx);
	} else if (isTxsHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeLogFilesSendHandlerForHA(ctx);
	} else if (isJarHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarReceiveHandlerForHA(ctx);
	} else if (isJasHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeJarSendHandlerForHA(ctx);
	}else if (isSdaHA(magic1, magic2, magic3)) {
		throwAwayReadUnsignedBytes(in);
		invokeAgentShutdownHandler(ctx);
	} else {
        // Unknown protocol; discard everything and close the connection.
        in.clear();
        ctx.close();
	}

	if (haEnabled) {
		syncExecutor.sync();
	}
}