io.netty.handler.timeout.IdleStateHandler Java Examples

The following examples show how to use io.netty.handler.timeout.IdleStateHandler. 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 check out the related API usage on the sidebar.
Example #1
Source File: WebSocketInitializer.java    From jeesupport with MIT License 6 votes vote down vote up
@Override
	protected void initChannel( SocketChannel _channel ) throws Exception {
		ChannelPipeline pipeline = _channel.pipeline();

		// 是否使用客户端模式
		if( CommonConfig.getBoolean( "jees.jsts.websocket.ssl.enable", false ) ){
			SSLEngine engine = sslContext1.createSSLEngine();
//			 是否需要验证客户端
			engine.setUseClientMode(false);
//			engine.setNeedClientAuth(false);
			pipeline.addFirst("ssl", new SslHandler( engine ));
		}

		pipeline.addLast( new IdleStateHandler( 100 , 0 , 0 , TimeUnit.SECONDS ) );
		pipeline.addLast( new HttpServerCodec() );
		pipeline.addLast( new ChunkedWriteHandler() );
		pipeline.addLast( new HttpObjectAggregator( 8192 ) );
		pipeline.addLast( new WebSocketServerProtocolHandler( CommonConfig.getString( ISocketBase.Netty_WebSocket_Url, "/" ) ) );
		pipeline.addLast( CommonContextHolder.getBean( WebSocketHandler.class ) );
	}
 
Example #2
Source File: NettyClient.java    From dapeng-soa with Apache License 2.0 6 votes vote down vote up
protected Bootstrap initBootstrap() {
    AbstractByteBufAllocator allocator =
            SoaSystemEnvProperties.SOA_POOLED_BYTEBUF ?
                    PooledByteBufAllocator.DEFAULT : UnpooledByteBufAllocator.DEFAULT;
    bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.ALLOCATOR, allocator);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds),
                    new SoaFrameDecoder(), //粘包和断包处理
                    new SoaIdleHandler(),
                    new SoaClientHandler(callBack));
        }
    });
    return bootstrap;
}
 
Example #3
Source File: Server.java    From zbus-server with MIT License 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {  
	ChannelPipeline p = ch.pipeline();  
	p.addLast(new IdleStateHandler(0, 0, idleTimeInSeconds)); 
	if(sslContext != null){
		p.addLast(sslContext.newHandler(ch.alloc()));
	}
	CodecInitializer initializer = getCodecInitializer();
	if(initializer != null){
		List<ChannelHandler> handlers = new ArrayList<>();
		initializer.initPipeline(handlers);
		for(ChannelHandler handler : handlers){
			 p.addLast(handler); 
		}
	}	 
	p.addLast(this.nettyToIoAdaptor);
}
 
Example #4
Source File: NettyClient.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
private Bootstrap createBootstrap() {
    return new Bootstrap().group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis())
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(
                            defaultEventExecutorGroup,
                            new NettyEncoder(),
                            new NettyDecoder(),
                            //*空闲状态的handler
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),
                            //管理连接的
                            new NettyConnetManageHandler(NettyClient.this),
                            //处理具体业务逻辑的handler
                            new NettyClientHandler(NettyClient.this));
                }
            });
}
 
Example #5
Source File: NettyServerInitializer.java    From netty-learning-example with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline ph = ch.pipeline();

    //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
    ph.addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
    // 解码和编码,应和客户端一致
    //传输的协议 Protobuf
    ph.addLast(new ProtobufVarint32FrameDecoder());
    ph.addLast(new ProtobufDecoder(UserMsg.User.getDefaultInstance()));
    ph.addLast(new ProtobufVarint32LengthFieldPrepender());
    ph.addLast(new ProtobufEncoder());

    //业务逻辑实现类
    ph.addLast("nettyServerHandler", new NettyServerHandler());
}
 
Example #6
Source File: NettyAcceptor.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 6 votes vote down vote up
private void initializePlainTcpTransport(IMessaging messaging, Properties props)
    throws IOException {
  final NettyMQTTHandler mqttHandler = new NettyMQTTHandler();
  final PubsubHandler handler = new PubsubHandler(pubsub, mqttHandler);
  handler.setMessaging(messaging);
  String host = props.getProperty(Constants.HOST_PROPERTY_NAME);
  int port = Integer.parseInt(props.getProperty(Constants.PORT_PROPERTY_NAME));
  initFactory(host, port, new PipelineInitializer() {
    @Override
    void init(ChannelPipeline pipeline) {
      pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0,
          Constants.DEFAULT_CONNECT_TIMEOUT));
      pipeline.addAfter("idleStateHandler", "idleEventHandler", new MoquetteIdleTimeoutHandler());
      //pipeline.addLast("logger", new LoggingHandler("Netty", LogLevel.ERROR));
      pipeline.addFirst("bytemetrics", new BytesMetricsHandler(bytesMetricsCollector));
      pipeline.addLast("decoder", new MQTTDecoder());
      pipeline.addLast("encoder", new MQTTEncoder());
      pipeline.addLast("metrics", new MessageMetricsHandler(metricsCollector));
      pipeline.addLast("handler", handler);
    }
  });
}
 
Example #7
Source File: ClientSocket.java    From OrionAlpha with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    encoder = new SocketEncoder(cipher);
    decoder = new SocketDecoder(cipher);
    channel.pipeline().addBefore("ClientSocket", "AliveAck", new IdleStateHandler(20, 15, 0));
    channel.pipeline().addBefore("ClientSocket", "SocketEncoder", encoder);
    channel.pipeline().addBefore("ClientSocket", "SocketDecoder", decoder);
    OutPacket packet = new OutPacket(Integer.MAX_VALUE);
    packet.encodeShort(14);
    packet.encodeShort(OrionConfig.CLIENT_VER);
    packet.encodeString(OrionConfig.CLIENT_PATCH);
    packet.encodeInt(cipher.getSeqRcv());
    packet.encodeInt(cipher.getSeqSnd());
    packet.encodeByte(OrionConfig.GAME_LOCALE);
    acceptTime = System.currentTimeMillis();
    channel.writeAndFlush(Unpooled.wrappedBuffer(packet.toArray()));
    super.channelActive(ctx);
}
 
Example #8
Source File: WebSocketServerInitializer.java    From SpringMVC-Project with MIT License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    //添加闲置处理,60秒没有数据传输,触发事件
    pipeline.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
    //将字节解码为HttpMessage对象,并将HttpMessage对象编码为字节
    pipeline.addLast(new HttpServerCodec());
    //出站数据压缩
    pipeline.addLast(new HttpContentCompressor());
    //聚合多个HttpMessage为单个FullHttpRequest
    pipeline.addLast(new HttpObjectAggregator(64 * 1024));
    //如果被请求的端点是/ws,则处理该升级握手
    pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    //聊天消息处理
    pipeline.addLast(new ChatServerHandler());
    //心跳处理
    pipeline.addLast(new HeartbeatHandler());
}
 
Example #9
Source File: TcpBroker.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
private Channel tcpServer(int port) throws Exception {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(this.bossGroup, this.workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline channelPipeline = socketChannel.pipeline();
                    channelPipeline.addFirst("idle", new IdleStateHandler(
                            0,
                            0,
                            weEventConfig.getKeepAlive()));

                    //channelPipeline.addLast("ssl", getSslHandler(sslContext, socketChannel.alloc()));
                    channelPipeline.addLast("decoder", new MqttDecoder());
                    channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                    channelPipeline.addLast("broker", new TcpHandler(protocolProcess));
                }
            });
    return serverBootstrap.bind(port).sync().channel();
}
 
Example #10
Source File: WebSocketServerInitializer.java    From litchi with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new WebSocketServerCompressionHandler());
    pipeline.addLast(new IdleStateHandler(0, 0, 60));
    pipeline.addLast(new WebSocketServerProtocolHandler(WEB_SOCKET_PATH, null, true));
    pipeline.addLast(new WebSocketHandler(litchi));

    for (ChannelHandler handler : handlers) {
        pipeline.addLast(handler);
    }
}
 
Example #11
Source File: NettyHttpServletPipelineFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected ChannelPipeline getDefaulHttpChannelPipeline(Channel channel) throws Exception {

        // Create a default pipeline implementation.
        ChannelPipeline pipeline = channel.pipeline();

        SslHandler sslHandler = configureServerSSLOnDemand();
        if (sslHandler != null) {
            LOG.log(Level.FINE,
                    "Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}",
                    sslHandler);
            pipeline.addLast("ssl", sslHandler);
        }

        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("aggregator", new HttpObjectAggregator(maxChunkContentSize));
        
        // Remove the following line if you don't want automatic content
        // compression.
        pipeline.addLast("deflater", new HttpContentCompressor());
        // Set up the idle handler
        pipeline.addLast("idle", new IdleStateHandler(nettyHttpServerEngine.getReadIdleTime(),
                nettyHttpServerEngine.getWriteIdleTime(), 0));

        return pipeline;
    }
 
Example #12
Source File: HttpServerInitializer.java    From jframe with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    // p.addLast("log", new LoggingHandler(LogLevel.ERROR));

    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast(new HttpRequestDecoder());
    p.addLast(new HttpResponseEncoder());
    p.addLast("http compressor", new HttpContentCompressor());
    // p.addLast(new HttpObjectAggregator(1048576));
    p.addLast("http dispatcher", reqDis);
    p.addLast("idleStateHandler", new IdleStateHandler(30, 10, 0));
    p.addLast("heartbeatHandler", new HeartbeatHandler());
}
 
Example #13
Source File: AbstractChannelInitializerTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_no_connect_idle_handler_default() throws Exception {

    final IdleStateHandler[] idleStateHandler = new IdleStateHandler[1];

    when(pipeline.addAfter(anyString(), anyString(), any(ChannelHandler.class))).thenAnswer(
            new Answer<ChannelPipeline>() {
                @Override
                public ChannelPipeline answer(final InvocationOnMock invocation) throws Throwable {

                    if (invocation.getArguments()[1].equals(NEW_CONNECTION_IDLE_HANDLER)) {
                        idleStateHandler[0] = (IdleStateHandler) (invocation.getArguments()[2]);
                    }
                    return pipeline;
                }
            });

    abstractChannelInitializer.initChannel(socketChannel);

    assertEquals(500, idleStateHandler[0].getReaderIdleTimeInMillis());
}
 
Example #14
Source File: TlsTcpChannelInitializer.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Override
protected void addSpecialHandlers(@NotNull final Channel ch) throws SslException {

    final int handshakeTimeout = tlsTcpListener.getTls().getHandshakeTimeout();
    final IdleStateHandler idleStateHandler = new IdleStateHandler(handshakeTimeout, 0, 0, TimeUnit.MILLISECONDS);
    final NoTlsHandshakeIdleHandler noTlsHandshakeIdleHandler = new NoTlsHandshakeIdleHandler(eventLog);
    if (handshakeTimeout > 0) {
        ch.pipeline().addLast(NEW_CONNECTION_IDLE_HANDLER, idleStateHandler);
        ch.pipeline().addLast(NO_TLS_HANDSHAKE_IDLE_EVENT_HANDLER, noTlsHandshakeIdleHandler);
    }

    final Tls tls = tlsTcpListener.getTls();
    final SslHandler sslHandler = sslFactory.getSslHandler(ch, tls);
    sslHandler.handshakeFuture().addListener(future -> {
        if (handshakeTimeout > 0) {
            ch.pipeline().remove(idleStateHandler);
            ch.pipeline().remove(noTlsHandshakeIdleHandler);
        }
        addNoConnectIdleHandlerAfterTlsHandshake(ch);
    });

    new SslInitializer(sslHandler, tls, eventLog, sslParameterHandler).addHandlers(ch);
}
 
Example #15
Source File: NettyRpcServerChannelInitializer.java    From tx-lcn with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    ch.pipeline().addLast(new LengthFieldPrepender(4, false));
    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));

    ch.pipeline().addLast(new IdleStateHandler(managerProperties.getCheckTime(),
            managerProperties.getCheckTime(), managerProperties.getCheckTime(), TimeUnit.MILLISECONDS));


    ch.pipeline().addLast(new ObjectSerializerEncoder());
    ch.pipeline().addLast(new ObjectSerializerDecoder());


    ch.pipeline().addLast(rpcCmdDecoder);
    ch.pipeline().addLast(new RpcCmdEncoder());
    ch.pipeline().addLast(socketManagerInitHandler);
    ch.pipeline().addLast(rpcAnswerHandler);
}
 
Example #16
Source File: ProxyClient.java    From proxy with MIT License 5 votes vote down vote up
/**
 * 连接代理服务器
 */
private void start() throws InterruptedException {

    initRealServerBoot();

    clientBootstrap.group(clientGroup).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                //初始化时将handler设置到ChannelPipeline
                @Override
                public void initChannel(SocketChannel ch) {
                    //ch.pipeline().addLast("logs", new LoggingHandler(LogLevel.DEBUG));
                    ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(10 * 3, 15 * 3, 20 * 3));
                    ch.pipeline().addLast(new ProxyMessageDecoder(2 * 1024 * 1024, 0, 4));
                    ch.pipeline().addLast(new ProxyMessageEncoder());
                    ch.pipeline().addLast(new LoginAuthReqHandler());
                    ch.pipeline().addLast(new HeartBeatReqHandler());
                    ch.pipeline().addLast(new ClientHandler(realServerBootstrap));
                    ch.pipeline().addLast(new MyHttpRequestDecoder());
                    ch.pipeline().addLast(new MyHttpObjectAggregator(maxContentLength));
                    ch.pipeline().addLast(new HttpReceiveHandler());
                }
            });

    /**
     * 最多尝试5次和服务端连接(总计数,不是连续尝试次数)
     */
    doConnect(5);

    try {
        clear();
    } catch (Exception ignored) {

    }

}
 
Example #17
Source File: KeepAliveManager.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
KeepAliveManager(final Channel channel, @Nullable final KeepAlivePolicy keepAlivePolicy) {
    this(channel, keepAlivePolicy, (task, delay, unit) ->
            channel.eventLoop().schedule(task, delay, unit),
            (ch, idlenessThresholdSeconds, onIdle) -> ch.pipeline().addLast(
                    new IdleStateHandler(idlenessThresholdSeconds, idlenessThresholdSeconds, 0) {
                        @Override
                        protected void channelIdle(final ChannelHandlerContext ctx, final IdleStateEvent evt) {
                            onIdle.run();
                        }
                    }));
}
 
Example #18
Source File: ProxyToServerConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize our {@link ChannelPipeline} to connect the upstream server.
 * LittleProxy acts as a client here.
 *
 * A {@link ChannelPipeline} invokes the read (Inbound) handlers in
 * ascending ordering of the list and then the write (Outbound) handlers in
 * descending ordering.
 *
 * Regarding the Javadoc of {@link HttpObjectAggregator} it's needed to have
 * the {@link HttpResponseEncoder} or {@link HttpRequestEncoder} before the
 * {@link HttpObjectAggregator} in the {@link ChannelPipeline}.
 *
 * @param pipeline
 * @param httpRequest
 */
private void initChannelPipeline(ChannelPipeline pipeline,
        HttpRequest httpRequest) {

    if (trafficHandler != null) {
        pipeline.addLast("global-traffic-shaping", trafficHandler);
    }

    pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
    pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);

    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("decoder", new HeadAwareHttpResponseDecoder(
    		proxyServer.getMaxInitialLineLength(),
            proxyServer.getMaxHeaderSize(),
            proxyServer.getMaxChunkSize()));

    // Enable aggregation for filtering if necessary
    int numberOfBytesToBuffer = proxyServer.getFiltersSource()
            .getMaximumResponseBufferSizeInBytes();
    if (numberOfBytesToBuffer > 0) {
        aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
    }

    pipeline.addLast("responseReadMonitor", responseReadMonitor);
    pipeline.addLast("requestWrittenMonitor", requestWrittenMonitor);

    // Set idle timeout
    pipeline.addLast(
            "idle",
            new IdleStateHandler(0, 0, proxyServer
                    .getIdleConnectionTimeout()));

    pipeline.addLast("handler", this);
}
 
Example #19
Source File: ClientToProxyConnection.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the {@link ChannelPipeline} for the client to proxy channel.
 * LittleProxy acts like a server here.
 * 
 * A {@link ChannelPipeline} invokes the read (Inbound) handlers in
 * ascending ordering of the list and then the write (Outbound) handlers in
 * descending ordering.
 * 
 * Regarding the Javadoc of {@link HttpObjectAggregator} it's needed to have
 * the {@link HttpResponseEncoder} or {@link io.netty.handler.codec.http.HttpRequestEncoder} before the
 * {@link HttpObjectAggregator} in the {@link ChannelPipeline}.
 * 
 * @param pipeline
 */
private void initChannelPipeline(ChannelPipeline pipeline) {
    LOG.debug("Configuring ChannelPipeline");

    pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
    pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);

    pipeline.addLast("encoder", new HttpResponseEncoder());
    // We want to allow longer request lines, headers, and chunks
    // respectively.
    pipeline.addLast("decoder", new HttpRequestDecoder(
            proxyServer.getMaxInitialLineLength(),
            proxyServer.getMaxHeaderSize(),
            proxyServer.getMaxChunkSize()));

    // Enable aggregation for filtering if necessary
    int numberOfBytesToBuffer = proxyServer.getFiltersSource()
            .getMaximumRequestBufferSizeInBytes();
    if (numberOfBytesToBuffer > 0) {
        aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
    }

    pipeline.addLast("requestReadMonitor", requestReadMonitor);
    pipeline.addLast("responseWrittenMonitor", responseWrittenMonitor);

    pipeline.addLast(
            "idle",
            new IdleStateHandler(0, 0, proxyServer
                    .getIdleConnectionTimeout()));

    pipeline.addLast("handler", this);
}
 
Example #20
Source File: FtdClientPool.java    From ftdc with Apache License 2.0 5 votes vote down vote up
@Override
  public void channelCreated(Channel ch) {
  	ch.pipeline().addLast(new FtdcDecoder());
ch.pipeline().addLast(new FtdcEncoder());
ch.pipeline().addLast(new IdleStateHandler(ApplicationRuntime.conf().getFtdcReaderIdle(), ApplicationRuntime.conf().getFtdcWriterIdle(), ApplicationRuntime.conf().getFtdcAllIdle(), TimeUnit.SECONDS));
ch.pipeline().addLast(new FtdHeartbeatHandler());
ch.pipeline().addLast(ApplicationRuntime.EEG, new FtdcHandler());
  }
 
Example #21
Source File: BattleServerInitializer.java    From Almost-Famous with MIT License 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline cp = ch.pipeline();
    cp.addLast("heartbeatHandler", new IdleStateHandler(battleServerConfig.getHeartBeatTime(), 0, 0, TimeUnit.SECONDS));
    cp.addLast("loggingHandler", new LoggingHandler(LogLevel.INFO));
    cp.addLast("decoder", new Decoder());
    cp.addLast("battleServerHandler", this.battleServerHandler);
    cp.addLast("encoder", new Encoder());
}
 
Example #22
Source File: ImapClient.java    From NioImapClient with Apache License 2.0 5 votes vote down vote up
private void startKeepAlive() {
  int keepAliveInterval = configuration.noopKeepAliveIntervalSec();
  if (keepAliveInterval > 0) {
    if (!connectionShutdown.get() && channel.pipeline().get(KEEP_ALIVE_HANDLER) == null) {
      this.channel.pipeline().addFirst(KEEP_ALIVE_HANDLER, new IdleStateHandler(keepAliveInterval, keepAliveInterval, keepAliveInterval));
    }
  }
}
 
Example #23
Source File: NettyServer.java    From openzaly with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {
	// SSLEngine sslEngine =
	// NettySocketSslContext.getInstance().getServerContext().createSSLEngine();

	channel.pipeline().addLast(new MessageDecoder());
	channel.pipeline().addLast(new MessageEncoder());
	channel.pipeline().addLast("timeout", new IdleStateHandler(60 * 5, 60 * 5, 60 * 5, TimeUnit.SECONDS));

	// ch.pipeline().addLast(new SslHandler(sslEngine));

	channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast("writeTimeoutHandler", new WriteTimeoutHandler(60 * 5, TimeUnit.SECONDS));
	channel.pipeline().addLast(new NettyServerHandler(executor));
}
 
Example #24
Source File: NettyChannelInitializer.java    From Kepler with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();

    if (GameConfiguration.getInstance().getBoolean("server.limit.bandwidth")) {
        long bandwidthLimit = GameConfiguration.getInstance().getLong("server.limit.bandwidth.amount");
        pipeline.addLast("trafficShapingHandler", new ChannelTrafficShapingHandler(bandwidthLimit, bandwidthLimit));
    }

    pipeline.addLast("gameEncoder", new NetworkEncoder());
    pipeline.addLast("gameDecoder", new NetworkDecoder());
    pipeline.addLast("handler", new ConnectionHandler(this.nettyServer));
    pipeline.addLast("idleStateHandler", new IdleStateHandler(60, 0, 0));
    pipeline.addLast("idleHandler", new IdleConnectionHandler());
}
 
Example #25
Source File: HttpRequester.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
   ChannelPipeline pipeline = ch.pipeline();
   if (sslCtx != null) {
       pipeline.addLast(sslCtx.newHandler(ch.alloc(), this.uri.getHost(), this.port));
   }
   pipeline.addLast(new IdleStateHandler(IDLE_TIMEOUT_SECONDS, IDLE_TIMEOUT_SECONDS, IDLE_TIMEOUT_SECONDS));
   pipeline.addLast(new HttpIdleStateHandler());
   pipeline.addLast(new HttpClientCodec());
   pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
   pipeline.addLast(new HttpClientHandler());
}
 
Example #26
Source File: RemotingNettyServer.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() {
    try {
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        bootstrap.option(ChannelOption.SO_REUSEADDR, true);
        bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
        bootstrap.localAddress(serverconfig.getListenPort());
        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws IOException {

                ch.pipeline().addLast("idleState", new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                ch.pipeline().addLast("heartbeat", new HeartbeatHandler());
                ch.pipeline().addLast(new KyroMsgDecoder());
                ch.pipeline().addLast(new KyroMsgEncoder());
                ch.pipeline().addLast("invoker", new NettyServerHandler());
            }
        });

        ChannelFuture channelFuture = this.bootstrap.bind().sync();
        //        channelFuture.channel().closeFuture().sync();
        logger.info("server started on port:" + serverconfig.getListenPort());
        respScheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                scanResponseTable(5000);
            }
        }, 60 * 1000, 60 * 1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        logger.error("", e);
        System.exit(-1);
    }
}
 
Example #27
Source File: UptimeClient.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    bs
            .group(group)
            .channel(NioSocketChannel.class)
            .remoteAddress(HOST, PORT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);
                }
            });
    bs.connect();
}
 
Example #28
Source File: NettyRpcClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void start(){
    b.group(group).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch)
                        throws Exception {
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1<<20, 0, 4, 0, 4),
                            new LengthFieldPrepender(4),
                            new RpcDecoder(Response.class), //
                            new RpcEncoder(Request.class), //
                            new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS),
                            new NettyConnHandler(),
                            new NettyClientHandler());
                }
            });

    this.scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5, new ThreadFactory() {
        private final AtomicInteger idGenerator = new AtomicInteger(0);
        @Override
        public Thread newThread(Runnable r) {

            return new Thread(r, "Rpc-Scheduled-" + this.idGenerator.incrementAndGet());
        }
    });


    this.scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            scanRpcFutureTable();
        }
    }, 500, 500, TimeUnit.MILLISECONDS);
}
 
Example #29
Source File: MqttServerImpl.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
private void initChannel(ChannelPipeline pipeline) {

    pipeline.addBefore("handler", "mqttEncoder", MqttEncoder.INSTANCE);
    if (this.options.getMaxMessageSize() > 0) {
      pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder(this.options.getMaxMessageSize()));
    } else {
      // max message size not set, so the default from Netty MQTT codec is used
      pipeline.addBefore("handler", "mqttDecoder", new MqttDecoder());
    }

    // adding the idle state handler for timeout on CONNECT packet
    pipeline.addBefore("handler", "idle", new IdleStateHandler(this.options.timeoutOnConnect(), 0, 0));
    pipeline.addBefore("handler", "timeoutOnConnect", new ChannelDuplexHandler() {

      @Override
      public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
          IdleStateEvent e = (IdleStateEvent) evt;
          if (e.state() == IdleState.READER_IDLE) {
            // as MQTT 3.1.1 describes, if no packet is sent after a "reasonable" time (here CONNECT timeout)
            // the connection is closed
            ctx.channel().close();
          }
        }
      }
    });
  }
 
Example #30
Source File: FrontendPipeline.java    From NettyReverseProxy with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    // 注册handler
    pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 0, 1,
            TimeUnit.MINUTES));
    pipeline.addLast(ApplicationContextUtil.getBean(FrontendDecode.class));
    pipeline.addLast(ApplicationContextUtil.getBean(FrontendEncode.class));
    pipeline.addLast(ApplicationContextUtil.getBean(ProxyFrontendHandler.class));

}