use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project java by wavefrontHQ.
the class HistogramLineIngester method initChannel.
@Override
protected void initChannel(Channel ch) throws Exception {
// Round robin channel to handler assignment.
int idx = (int) (Math.abs(connectionId.getAndIncrement()) % handlers.size());
ChannelHandler handler = handlers.get(idx);
// Add decoders and timeout, add handler()
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(MAXIMUM_FRAME_LENGTH, true, false), new StringDecoder(Charsets.UTF_8), new IdleStateHandler(CHANNEL_IDLE_TIMEOUT_IN_SECS_DEFAULT, 0, 0), new ChannelDuplexHandler() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
logger.warning("terminating connection to histogram client due to inactivity after " + CHANNEL_IDLE_TIMEOUT_IN_SECS_DEFAULT + "s: " + ctx.channel());
ctx.close();
}
}
}
}, handler);
}
use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project web3sdk by FISCO-BCOS.
the class ChannelConnections method startConnect.
public void startConnect() {
if (running) {
logger.debug("服务已启动");
return;
}
logger.debug("初始化connections connect");
// 初始化netty
EventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
final ChannelConnections selfService = this;
final ThreadPoolTaskExecutor selfThreadPool = threadPool;
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
final Resource keystoreResource = resolver.getResource(getClientKeystorePath());
final Resource caResource = resolver.getResource(getCaCertPath());
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
InputStream ksInputStream = keystoreResource.getInputStream();
ks.load(ksInputStream, getKeystorePassWord().toCharArray());
/*
* 每次连接使用新的handler 连接信息从socketChannel中获取
*/
ChannelHandler handler = new ChannelHandler();
handler.setConnections(selfService);
handler.setIsServer(false);
handler.setThreadPool(selfThreadPool);
SslContext sslCtx = SslContextBuilder.forClient().trustManager(caResource.getFile()).keyManager((PrivateKey) ks.getKey("client", getClientCertPassWord().toCharArray()), (X509Certificate) ks.getCertificate("client")).build();
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new LengthFieldBasedFrameDecoder(1024 * 1024 * 4, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
}
});
running = true;
Thread loop = new Thread() {
public void run() {
try {
while (true) {
if (!running) {
return;
}
// 尝试重连
reconnect();
Thread.sleep(heartBeatDelay);
}
} catch (InterruptedException e) {
logger.error("系统错误", e);
}
}
};
loop.start();
}
use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project web3sdk by FISCO-BCOS.
the class ChannelConnections method startConnect.
public void startConnect() throws Exception {
if (running) {
logger.debug("running");
return;
}
logger.debug(" start connect. ");
// init netty
EventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
// set connect timeout
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
final ChannelConnections selfService = this;
final ThreadPoolTaskExecutor selfThreadPool = threadPool;
SslContext sslContext = (EncryptType.encryptType == EncryptType.ECDSA_TYPE) ? initSslContext() : initSMSslContext();
SslContext finalSslContext = sslContext;
bootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
/*
* Each connection is fetched from the socketChannel, using the new
* handler connection information
*/
ChannelHandler handler = new ChannelHandler();
handler.setConnections(selfService);
handler.setThreadPool(selfThreadPool);
SslHandler sslHandler = finalSslContext.newHandler(ch.alloc());
/**
* set ssl handshake timeout
*/
sslHandler.setHandshakeTimeoutMillis(sslHandShakeTimeout);
ch.pipeline().addLast(sslHandler, new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, -4, 0), new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS), handler);
}
});
List<Tuple3<String, Integer, ChannelFuture>> tuple3List = new ArrayList<>();
// try to connect to all nodes
for (ConnectionInfo connectionInfo : connections) {
String IP = connectionInfo.getHost();
Integer port = connectionInfo.getPort();
ChannelFuture channelFuture = bootstrap.connect(IP, port);
tuple3List.add(new Tuple3<>(IP, port, channelFuture));
}
boolean atLeastOneConnectSuccess = false;
List<String> errorMessageList = new ArrayList<>();
// Wait for all connection operations to complete
for (Tuple3<String, Integer, ChannelFuture> tuple3 : tuple3List) {
ChannelFuture connectFuture = tuple3.getValue3().awaitUninterruptibly();
if (!connectFuture.isSuccess()) {
logger.error(" connect to {}:{}, error: {}", tuple3.getValue1(), tuple3.getValue2(), connectFuture.cause().getMessage());
String connectFailedMessage = Objects.isNull(connectFuture.cause()) ? "connect to " + tuple3.getValue1() + ":" + tuple3.getValue2() + " failed" : connectFuture.cause().getMessage();
errorMessageList.add(connectFailedMessage);
} else {
// tcp connect success and waiting for SSL handshake
logger.trace(" connect to {}:{} success", tuple3.getValue1(), tuple3.getValue2());
SslHandler sslhandler = connectFuture.channel().pipeline().get(SslHandler.class);
if (Objects.isNull(sslhandler)) {
String sslHandshakeFailedMessage = " ssl handshake failed:/" + tuple3.getValue1() + ":" + tuple3.getValue2();
logger.debug(" SslHandler is null, host: {}, port: {}", tuple3.getValue1(), tuple3.getValue2());
errorMessageList.add(sslHandshakeFailedMessage);
continue;
}
Future<Channel> sshHandshakeFuture = sslhandler.handshakeFuture().awaitUninterruptibly();
if (sshHandshakeFuture.isSuccess()) {
atLeastOneConnectSuccess = true;
logger.trace(" ssl handshake success {}:{}", tuple3.getValue1(), tuple3.getValue2());
} else {
String sslHandshakeFailedMessage = " ssl handshake failed:/" + tuple3.getValue1() + ":" + tuple3.getValue2();
errorMessageList.add(sslHandshakeFailedMessage);
}
}
}
// All connections failed
if (!atLeastOneConnectSuccess) {
logger.error(" all connections have failed, " + errorMessageList.toString());
throw new RuntimeException(" Failed to connect to nodes: " + errorMessageList.toString() + helpInfo);
}
running = true;
logger.debug(" start connect end. ");
}
use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project summer by foxsugar.
the class SocketServerInitializer method initChannel.
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
// p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast("encoder", new GameCharsEncoder());
p.addLast("decoder", new GameCharsDecoder());
p.addLast("timeout", new IdleStateHandler(15, 0, 0, TimeUnit.SECONDS));
// p.addLast(new SocketHandler());
p.addLast("gameHandler", new GameMsgHandler());
}
use of org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler in project dubbo by alibaba.
the class QosProcessHandler method decode.
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
if (in.readableBytes() < 1) {
return;
}
// read one byte to guess protocol
final int magic = in.getByte(in.readerIndex());
ChannelPipeline p = ctx.pipeline();
p.addLast(new LocalHostPermitHandler(acceptForeignIp));
if (isHttp(magic)) {
// no welcome output for http protocol
if (welcomeFuture != null && welcomeFuture.isCancellable()) {
welcomeFuture.cancel(false);
}
p.addLast(new HttpServerCodec());
p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpProcessHandler());
p.remove(this);
} else {
p.addLast(new LineBasedFrameDecoder(2048));
p.addLast(new StringDecoder(CharsetUtil.UTF_8));
p.addLast(new StringEncoder(CharsetUtil.UTF_8));
p.addLast(new IdleStateHandler(0, 0, 5 * 60));
p.addLast(new TelnetIdleEventHandler());
p.addLast(new TelnetProcessHandler());
p.remove(this);
}
}
Aggregations