io.netty.handler.timeout.ReadTimeoutHandler的实例源码

项目:Cobweb    文件:Client.java   
/**
 * 本地爬虫服务,长连接
 *
 * @param action
 */
public Client(@Nonnull final Action action){
    isLongConnection = true;
    final Client self = this;
    this.action = action;
    channelInitializer = new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
            ch.pipeline().addLast(new ProtobufDecoder(ProcessData.getDefaultInstance()));
            ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
            ch.pipeline().addLast(new ProtobufEncoder());
            ch.pipeline().addLast(new ReadTimeoutHandler(60));
            ch.pipeline().addLast(new LoginAuthReqHandler(channel));
            ch.pipeline().addLast(new LocalCrawlerHandler(action));
            ch.pipeline().addLast(new HeartBeatReqHandler(self,closeLongConnection));
        }
    };
}
项目:fresco_floodlight    文件:RPCChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager,rpcService);

    IdleStateHandler idleHandler = 
            new IdleStateHandler(5,10,0);
    ReadTimeoutHandler readTimeoutHandler = 
            new ReadTimeoutHandler(30);

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("idle",idleHandler);
    pipeline.addLast("timeout",readTimeoutHandler);
    pipeline.addLast("handshaketimeout",new HandshakeTimeoutHandler(channelHandler,timer,10));

    pipeline.addLast("syncMessageDecoder",new SyncMessageDecoder(maxFrameSize));
    pipeline.addLast("syncMessageEncoder",new SyncMessageEncoder());

    pipeline.addLast("handler",channelHandler);
}
项目:onedatashare    文件:HTTPInitializer.java   
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL",new SslHandler(sslEng,false));
  }

  pipe.addFirst("Timer",new ReadTimeoutHandler(30));
  pipe.addLast("Codec",new HttpClientCodec());
  pipe.addLast("Inflater",new HttpContentDecompressor());
  pipe.addLast("Handler",new HTTPMessageHandler(builder));
}
项目:Stork    文件:HTTPInitializer.java   
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL",new HTTPMessageHandler(builder));
}
项目:webapp-tyust    文件:NettyServer.java   
private NettyServer(){
    pGroup = new NioEventLoopGroup();
    cGroup = new NioEventLoopGroup();
    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(pGroup,cGroup)
     .channel(NioServerSocketChannel.class)
     .option(ChannelOption.SO_BACKLOG,1024)
     //设置日志
     .handler(new LoggingHandler(LogLevel.INFO))
     .childHandler(new ChannelInitializer<SocketChannel>() {
        protected void initChannel(SocketChannel sc) throws Exception {
            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
            sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
            sc.pipeline().addLast(new ReadTimeoutHandler(60));
            sc.pipeline().addLast(new NettyServerHandler());
        }
    });     
}
项目:SDN-Multicast    文件:RPCChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager,channelHandler);
}
项目:arscheduler    文件:RPCChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager,channelHandler);
}
项目:Waterfall-Old    文件:PipelineUtils.java   
@Override
public void initChannel(Channel ch) throws Exception
{
    try
    {
        ch.config().setOption( ChannelOption.IP_TOS,0x18 );
    } catch ( ChannelException ex )
    {
        // IP_TOS is not supported (Windows XP / Windows Server 2003)
    }
    ch.config().setOption( ChannelOption.TCP_NODELAY,true );
    ch.config().setAllocator( PooledByteBufAllocator.DEFAULT );

    ch.pipeline().addLast( TIMEOUT_HANDLER,new ReadTimeoutHandler( BungeeCord.getInstance().config.getTimeout(),TimeUnit.MILLISECONDS ) );
    ch.pipeline().addLast( FRAME_DECODER,new Varint21FrameDecoder() );
    ch.pipeline().addLast( FRAME_PREPENDER,framePrepender );

    ch.pipeline().addLast( BOSS_HANDLER,new HandlerBoss() );
}
项目:floodlight1.2-delay    文件:RPCChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager,channelHandler);
}
项目:floodlight-hardware    文件:RPCChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler =
            new RPCChannelHandler(syncManager,rpcService);

    IdleStateHandler idleHandler =
            new IdleStateHandler(5,0);
    ReadTimeoutHandler readTimeoutHandler =
            new ReadTimeoutHandler(30);

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("idle",channelHandler);
}
项目:ACAMPController    文件:RPCChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager,channelHandler);
}
项目:SI    文件:HttpServerInitializer.java   
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    // Uncomment the following line if you don't want to handle HttpChunks.
    //pipeline.addLast("chunkedWriter",new ChunkedWriteHandler());
    //p.addLast(new HttpObjectAggregator(1048576));
    // Remove the following line if you don't want automatic content compression.
    //pipeline.addLast(new HttpContentCompressor());

    // Uncomment the following line if you don't want to handle HttpContents.
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast("readTimeoutHandler",new ReadTimeoutHandler(READ_TIMEOUT));
    pipeline.addLast("myHandler",new MyHandler());

    pipeline.addLast("handler",new HttpServerHandler(listener));
}
项目:UniversalProxy    文件:PipelineUtils.java   
@Override
public void initChannel(Channel ch) throws Exception
{
    try
    {
        ch.config().setOption( ChannelOption.IP_TOS,new HandlerBoss() );
}
项目:nomulus    文件:EppProtocolModule.java   
@Provides
@EppProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
    Provider<SslServerInitializer<NioSocketChannel>> sslServerInitializerProvider,Provider<ProxyProtocolHandler> proxyProtocolHandlerProvider,@EppProtocol Provider<ReadTimeoutHandler> readTimeoutHandlerProvider,Provider<LengthFieldBasedFrameDecoder> lengthFieldBasedFrameDecoderProvider,Provider<LengthFieldPrepender> lengthFieldPrependerProvider,Provider<EppServiceHandler> eppServiceHandlerProvider,Provider<LoggingHandler> loggingHandlerProvider,Provider<FullHttpRequestRelayHandler> relayHandlerProvider) {
  return ImmutableList.of(
      proxyProtocolHandlerProvider,sslServerInitializerProvider,readTimeoutHandlerProvider,lengthFieldBasedFrameDecoderProvider,lengthFieldPrependerProvider,eppServiceHandlerProvider,loggingHandlerProvider,relayHandlerProvider);
}
项目:etcd4j    文件:EtcdNettyClient.java   
/**
 * Modify the pipeline for the request
 *
 * @param req      to process
 * @param pipeline to modify
 * @param <R>      Type of Response
 */
private <R> void modifyPipeLine(final EtcdRequest<R> req,final ChannelPipeline pipeline) {
  final EtcdResponseHandler<R> handler = new EtcdResponseHandler<>(this,req);

  if (req.hasTimeout()) {
    pipeline.addFirst(new ReadTimeoutHandler(req.getTimeout(),req.getTimeoutUnit()));
  }

  pipeline.addLast(handler);
  pipeline.addLast(new ChannelHandlerAdapter() {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
      handler.retried(true);
      req.getPromise().handleRetry(cause);
    }
  });
}
项目:Pistachio    文件:NettyPistachioClientInitializer.java   
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc(),NettyPistachioClient.HOST,NettyPistachioClient.PORT));
    }

    LogLevel level = LogLevel.DEBUG;


    p.addLast(new LoggingHandler(level));
    p.addLast(new ReadTimeoutHandler(ConfigurationManager.getConfiguration().getInt("Network.Netty.ClientReadTimeoutMillis",10000),TimeUnit.MILLISECONDS));
    p.addLast(new ProtobufVarint32FrameDecoder());
    p.addLast(new ProtobufDecoder(NettyPistachioProtocol.Response.getDefaultInstance()));

    p.addLast(new ProtobufVarint32LengthFieldPrepender());
    p.addLast(new ProtobufEncoder());

    p.addLast(new NettyPistachioClientHandler());
}
项目:ThinkMap    文件:ServerChannelInitializer.java   
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast("timeout",new ReadTimeoutHandler(15));
    pipeline.addLast("codec-http",new HttpServerCodec());
    pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
    pipeline.addLast("handler",new HTTPHandler(plugin));
    pipeline.addLast("websocket",new WebSocketServerProtocolHandler("/server"));
    pipeline.addLast("packet-decoder",new PacketDecoder());
    pipeline.addLast("packet-encoder",new PacketEncoder());
    pipeline.addLast("packet-handler",new ClientHandler(socketChannel,plugin));

    socketChannel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    plugin.getWebHandler().getChannelGroup().add(socketChannel);
}
项目:IngotEngine    文件:NetManager.java   
public void start() {
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            public void initChannel(SocketChannel ch) throws Exception {
                IngotPlayer ingotPlayer = new IngotPlayer(ch);
                ch.pipeline().addLast(new ReadTimeoutHandler(15));
                ch.pipeline().addLast(new VarIntCodec());
                ch.pipeline().addLast(ingotPlayer.packetCodec);
            }
        });
        b.option(ChannelOption.SO_BACKLOG,16);
        b.childOption(ChannelOption.SO_KEEPALIVE,true);
        future = b.bind(25565);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:laputa    文件:LaputaServerInitializer.java   
@Override
public void initChannel(SocketChannel ch) {
  ChannelPipeline p = ch.pipeline();
  p.addLast(new ReadTimeoutHandler(60,TimeUnit.SECONDS));
  if (sslContext != null) {
    p.addLast(sslContext.newHandler(ch.alloc()));
  }
  p.addLast(new HttpContentCompressor(5));
  p.addLast(new HttpServerCodec());
  p.addLast(new HttpObjectAggregator(1048576));
  p.addLast(new ChunkedWriteHandler());
  if (null != corsConfig) {
    p.addLast(new CorsHandler(corsConfig));
  }
  p.addLast(new WebSocketServerCompressionHandler());
  p.addLast(new WebSocketServerProtocolHandler(webSocketPath,null,true));
  p.addLast(new LaputaServerHandler(null != sslContext,requestProcessor));
}
项目:stork    文件:HTTPInitializer.java   
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL",new HTTPMessageHandler(builder));
}
项目:CentauriCloud    文件:OpenCloudChannelInitializer.java   
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    channel.pipeline()
            .addLast(new ReadTimeoutHandler(30))
            .addLast("splitter",new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4))
            .addLast(new PacketDecoder())
            .addLast("prepender",new LengthFieldPrepender(4))
            .addLast(new PacketEncoder())
            .addLast(client.getHandler());
    this.client.setChannel(channel);
    System.out.println("Netty client started");
}
项目:talchain    文件:Channel.java   
public void init(ChannelPipeline pipeline,String remoteId,boolean discoveryMode,ChannelManager channelManager) {
        this.channelManager = channelManager;
        this.remoteId = remoteId;

        isActive = remoteId != null && !remoteId.isEmpty();

        pipeline.addLast("readTimeoutHandler",new ReadTimeoutHandler(config.peerChannelReadTimeout(),TimeUnit.SECONDS));
        pipeline.addLast(stats.tcp);
        pipeline.addLast("handshakeHandler",handshakeHandler);

        this.discoveryMode = discoveryMode;

        if (discoveryMode) {
            // temporary key/nodeId to not accidentally smear our reputation with
            // unexpected disconnect
//            handshakeHandler.generateTempKey();
        }

        handshakeHandler.setRemoteId(remoteId,this);

        messageCodec.setChannel(this);

        msgQueue.setChannel(this);

        p2pHandler.setMsgQueue(msgQueue);
        messageCodec.setP2pMessageFactory(new P2pMessageFactory());

        shhHandler.setMsgQueue(msgQueue);
        messageCodec.setShhMessageFactory(new ShhMessageFactory());

        bzzHandler.setMsgQueue(msgQueue);
        messageCodec.setBzzMessageFactory(new BzzMessageFactory());
    }
项目:mqttserver    文件:ConnectProcesser.java   
@Override
public Message process(Message msg,ChannelHandlerContext ctx) {
  ConnectMessage cm = (ConnectMessage) msg;
  if (!MQTTProtocol.isValid(cm.getProtocolId()) || !MQTTVersion.isValid(cm.getProtocolVersion())) {
    return UNACCEPTABLE_PROTOCOL_VERSION;
  }

  int timeout = (int) Math.ceil(cm.getKeepAlive() * 1.5);

  ctx.pipeline().addFirst("readTimeOutHandler",new ReadTimeoutHandler(timeout,TimeUnit.SECONDS));

  MemoryMetaPool.registerClienId(cm.getClientId(),ctx.channel());

  return ACCEPTED;
}
项目:netty-socks    文件:Socks5WorkerChannelInitializer.java   
@Override
protected void initChannel(io.netty.channel.socket.SocketChannel channel) throws Exception {
    ChannelPipeline pipeline = channel.pipeline();

    // 连接管理
    pipeline.addLast(ConnectionManageHandler.NAME,new ConnectionManageHandler(3000));

    // 空闲超时
    pipeline.addLast(new IdleStateHandler(10,0));
    pipeline.addLast(new IdleStateEventHandler());

    // 读写超时
    pipeline.addLast(new ReadTimeoutHandler(socksProperties.getReadTimeoutMillis(),TimeUnit.MILLISECONDS));
    pipeline.addLast(new WriteTimeoutHandler(socksProperties.getWriteTimeoutMillis(),TimeUnit.MILLISECONDS));

    // netty log
    //pipeline.addLast(new LoggingHandler());

    // 负责将输出的 Socks5Message 转为 ByteBuf
    pipeline.addLast(Socks5ServerEncoder.DEFAULT);

    // init
    pipeline.addLast(Socks5InitialRequestDecoder.class.getName(),new Socks5InitialRequestDecoder());
    pipeline.addLast(Socks5InitialRequestHandler.class.getName(),socks5InitialRequestHandler);

    // auth
    if (socks5PasswordAuthRequestHandler != null) {
        pipeline.addLast(Socks5PasswordAuthRequestDecoder.class.getName(),new Socks5PasswordAuthRequestDecoder());
        pipeline.addLast(Socks5PasswordAuthRequestHandler.class.getName(),socks5PasswordAuthRequestHandler);
    }

    // connection
    pipeline.addLast(Socks5CommandRequestDecoder.class.getName(),new Socks5CommandRequestDecoder());
    pipeline.addLast(Socks5CommandRequestHandler.class.getName(),socks5CommandRequestHandler);
}
项目:DecompiledMinecraft    文件:NetworkManager.java   
public static NetworkManager func_181124_a(InetAddress p_181124_0_,int p_181124_1_,boolean p_181124_2_)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    Class <? extends SocketChannel > oclass;
    LazyLoadBase <? extends EventLoopGroup > lazyloadbase;

    if (Epoll.isAvailable() && p_181124_2_)
    {
        oclass = EpollSocketChannel.class;
        lazyloadbase = field_181125_e;
    }
    else
    {
        oclass = NioSocketChannel.class;
        lazyloadbase = CLIENT_NIO_EVENTLOOP;
    }

    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
    {
        protected void initChannel(Channel p_initChannel_1_) throws Exception
        {
            try
            {
                p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY,Boolean.valueOf(true));
            }
            catch (ChannelException var3)
            {
                ;
            }

            p_initChannel_1_.pipeline().addLast((String)"timeout",(ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter",(ChannelHandler)(new MessageDeserializer2())).addLast((String)"decoder",(ChannelHandler)(new MessageDeserializer(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender",(ChannelHandler)(new MessageSerializer2())).addLast((String)"encoder",(ChannelHandler)(new MessageSerializer(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler",(ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(p_181124_0_,p_181124_1_).syncUninterruptibly();
    return networkmanager;
}
项目:Cobweb    文件:Server.java   
public void bind() {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    try {
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                        ch.pipeline().addLast(new ProtobufDecoder(ProcessData.getDefaultInstance()));
                        ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                        ch.pipeline().addLast(new ProtobufEncoder());
                        ch.pipeline().addLast(new ReadTimeoutHandler(60));
                        ch.pipeline().addLast(new LoginAuthRespHandler(channels));
                        ch.pipeline().addLast(new ShellRespHandler(client,dfsManager));
                        ch.pipeline().addLast(new WorkerProxyHandler(worker));
                        ch.pipeline().addLast(new HeartBeatRespHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
        logger.error(e.getMessage());
    }
}
项目:BaseClient    文件:NetworkManager.java   
public static NetworkManager func_181124_a(InetAddress p_181124_0_,p_181124_1_).syncUninterruptibly();
    return networkmanager;
}
项目:NioImapClient    文件:ImapClient.java   
private void configureChannel() {
  this.channel.pipeline()
      .addLast(new ReadTimeoutHandler(configuration.socketTimeoutMs(),TimeUnit.MILLISECONDS))
      .addLast(new ResponseDecoder(configuration,clientState,promiseExecutor))
      .addLast(codec)
      .addLast(promiseExecutor,this)
      .addLast(promiseExecutor,this.clientState);

  this.channel.attr(ImapChannelAttrs.CONFIGURATION).set(configuration);
}
项目:nearenough    文件:NettyClient.java   
public static void main(String[] args) throws InterruptedException,NoSuchAlgorithmException {
  InetSocketAddress addr = new InetSocketAddress(GOOGLE_SERVER_HOST,GOOGLE_SERVER_PORT);

  System.out.printf("Sending request to %s\n",addr);

  // Below is Netty boilerplate for setting-up an event loop and registering a handler

  NioEventLoopGroup group = new NioEventLoopGroup();
  Bootstrap bootstrap = new Bootstrap()
      .group(group)
      .remoteAddress(addr)
      .channel(NioDatagramChannel.class)
      .handler(new ChannelInitializer<NioDatagramChannel>() {
        @Override
        protected void initChannel(NioDatagramChannel ch) throws Exception {
          ch.pipeline()
              .addLast(new ReadTimeoutHandler(5))
              .addLast(new RequestHandler(addr));
        }
      });

  ChannelFuture connectFuture = bootstrap.connect();
  connectFuture.addListener(fut -> {
    if (!fut.isSuccess()) {
      System.out.println("Connect fail:");
      System.out.println(fut.cause().getMessage());
    }
  });

  connectFuture.channel().closeFuture().sync();
  group.shutdownGracefully();
}
项目:aws-sdk-java-v2    文件:RunnableRequest.java   
private void makeRequest(HttpRequest request) {
    log.debug("Writing request: {}",request);
    channel.pipeline().addFirst(new WriteTimeoutHandler(context.configuration().writeTimeout()));
    channel.writeAndFlush(new StreamedRequest(request,context.sdkRequestProvider(),channel))
           .addListener(wireCall -> {
               ChannelUtils.removeIfExists(channel.pipeline(),WriteTimeoutHandler.class);
               if (wireCall.isSuccess()) {
                   channel.pipeline().addFirst(new ReadTimeoutHandler(context.configuration().readTimeout()));
                   // Auto-read is turned off so trigger an explicit read to give control to HttpStreamsClientHandler
                   channel.read();
               } else {
                   handleFailure(() -> "Failed to make request to " + endpoint(),wireCall.cause());
               }
           });
}
项目:aws-sdk-java-v2    文件:ChannelPipelineInitializer.java   
@Override
public void channelReleased(Channel ch) throws Exception {
    // Remove any existing handlers from the pipeline from the previous request.
    ChannelUtils.removeIfExists(ch.pipeline(),HttpStreamsClientHandler.class,ResponseHandler.class,ReadTimeoutHandler.class,WriteTimeoutHandler.class);
}
项目:EMC    文件:OAuthNetworkManager.java   
public static OAuthNetworkManager createNetworkManagerAndConnect(InetAddress address,int serverPort,boolean useNativeTransport,OAuthCallback callback) {
    final OAuthNetworkManager networkmanager = new OAuthNetworkManager(EnumPacketDirection.CLIENTBOUND,callback);
    Class<? extends SocketChannel> oclass;
    LazyLoadBase<? extends EventLoopGroup> lazyloadbase;

    if (Epoll.isAvailable() && useNativeTransport) {
        oclass = EpollSocketChannel.class;
        lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
    } else {
        oclass = NioSocketChannel.class;
        lazyloadbase = CLIENT_NIO_EVENTLOOP;
    }

    (new Bootstrap()).group(lazyloadbase.getValue()).handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel p_initChannel_1_) throws Exception {
            try {
                p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY,Boolean.valueOf(true));
            } catch (ChannelException var3) {
                ;
            }

            p_initChannel_1_.pipeline().addLast("timeout",new ReadTimeoutHandler(30))
                    .addLast("splitter",new NettyVarint21FrameDecoder())
                    .addLast("decoder",new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))
                    .addLast("prepender",new NettyVarint21FrameEncoder())
                    .addLast("encoder",new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))
                    .addLast("packet_handler",networkmanager);
        }
    }).channel(oclass).connect(address,serverPort).syncUninterruptibly();
    return networkmanager;
}
项目:AppCoins-ethereumj    文件:Channel.java   
public void init(ChannelPipeline pipeline,this);

        messageCodec.setChannel(this);

        msgQueue.setChannel(this);

        p2pHandler.setMsgQueue(msgQueue);
        messageCodec.setP2pMessageFactory(new P2pMessageFactory());

        shhHandler.setMsgQueue(msgQueue);
        messageCodec.setShhMessageFactory(new ShhMessageFactory());

        bzzHandler.setMsgQueue(msgQueue);
        messageCodec.setBzzMessageFactory(new BzzMessageFactory());
    }
项目:fresco_floodlight    文件:OFChannelInitializer.java   
@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    OFChannelHandler handler = new OFChannelHandler(
            switchManager,connectionListener,pipeline,debugCounters,ofBitmaps,defaultFactory);

    if (keyStore != null && keyStorePassword != null) {
        try {
            /* Set up factories and stores. */
            TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore tmpKS = null;
            tmFactory.init(tmpKS);

            /* Use keystore/pass defined in properties file. */
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(keyStore),keyStorePassword.toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks,keyStorePassword.toCharArray());

            KeyManager[] km = kmf.getKeyManagers();
            TrustManager[] tm = tmFactory.getTrustManagers();

            /* Set up SSL prereqs for Netty. */
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(km,tm,null);
            SSLEngine sslEngine = sslContext.createSSLEngine();

            /* We are the server and we will create secure sessions. */
            sslEngine.setUseClientMode(false);
            sslEngine.setEnableSessionCreation(true);

            /* These are redundant (default),but for clarity... */
            sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); 
            sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());

            /* First,decrypt w/handler+engine; then,proceed with rest of handlers. */
            pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER,new SslHandler(sslEngine));
            log.info("SSL OpenFlow socket initialized and handler ready for switch.");
        } catch (Exception e) { /* There are lots of possible exceptions to catch,so this should get them all. */
            log.error("Exception initializing SSL OpenFlow socket: {}",e.getMessage());
            throw e; /* If we wanted secure but didn't get it,we should bail. */
        }
    }

    pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER,new OFMessageDecoder());
    pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER,new OFMessageEncoder());
    pipeline.addLast(PipelineHandler.MAIN_IDLE,new IdleStateHandler(PipelineIdleReadTimeout.MAIN,PipelineIdleWriteTimeout.MAIN,0));
    pipeline.addLast(PipelineHandler.READ_TIMEOUT,new ReadTimeoutHandler(30));
    pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,new HandshakeTimeoutHandler(
                    handler,PipelineHandshakeTimeout.CHANNEL));

    pipeline.addLast(PipelineHandler.CHANNEL_HANDLER,handler);
}
项目:Backmemed    文件:NetworkManager.java   
/**
 * Create a new NetworkManager from the server host and connect it to the server
 */
public static NetworkManager createNetworkManagerAndConnect(InetAddress address,boolean useNativeTransport)
{
    final NetworkManager networkmanager = new NetworkManager(EnumPacketDirection.CLIENTBOUND);
    Class <? extends SocketChannel > oclass;
    LazyLoadBase <? extends EventLoopGroup > lazyloadbase;

    if (Epoll.isAvailable() && useNativeTransport)
    {
        oclass = EpollSocketChannel.class;
        lazyloadbase = CLIENT_EPOLL_EVENTLOOP;
    }
    else
    {
        oclass = NioSocketChannel.class;
        lazyloadbase = CLIENT_NIO_EVENTLOOP;
    }

    ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer<Channel>()
    {
        protected void initChannel(Channel p_initChannel_1_) throws Exception
        {
            try
            {
                p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY,(ChannelHandler)(new NettyVarint21FrameDecoder())).addLast((String)"decoder",(ChannelHandler)(new NettyPacketDecoder(EnumPacketDirection.CLIENTBOUND))).addLast((String)"prepender",(ChannelHandler)(new NettyVarint21FrameEncoder())).addLast((String)"encoder",(ChannelHandler)(new NettyPacketEncoder(EnumPacketDirection.SERVERBOUND))).addLast((String)"packet_handler",(ChannelHandler)networkmanager);
        }
    })).channel(oclass)).connect(address,serverPort).syncUninterruptibly();
    return networkmanager;
}
项目:CustomWorldGen    文件:NetworkManager.java   
/**
 * Create a new NetworkManager from the server host and connect it to the server
 */
@SideOnly(Side.CLIENT)
public static NetworkManager createNetworkManagerAndConnect(InetAddress address,serverPort).syncUninterruptibly();
    return networkmanager;
}
项目:UnknownPandaServer    文件:ConnectionInitializer.java   
@Override
protected void initChannel(Channel channel) throws Exception {
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast("timeout",new ReadTimeoutHandler(10));

    NetworkManager networkManager = new NetworkManager(connectionProvider.getCore());
    pipeline.addLast("packet_codec",new PacketCodec(networkManager.getProtocolManager()));
    pipeline.addLast("network_manager",networkManager);

    for (ConnectionInitListener initializerListener : connectionProvider.getInitializerListeners()) {
        initializerListener.init(networkManager);
    }
}
项目:Apex    文件:ApexSocketChannelInitializer.java   
@Override
protected void initChannel(SocketChannel channel) throws Exception {

    BackendInfo backendInfo = Apex.getBalancingStrategy()
            .selectBackend(channel.remoteAddress().getHostName(),channel.remoteAddress().getPort());

    if (backendInfo == null) {
        // Gracefully close the channel
        channel.close();

        logger.error("Unable to select a backend server. All down?");
        return;
    }

    channel.pipeline()
            .addLast(new ReadTimeoutHandler(readTimeout))
            .addLast(new WriteTimeoutHandler(writeTimeout));

    GlobalTrafficShapingHandler trafficShapingHandler = Apex.getInstance().getTrafficShapingHandler();
    if (trafficShapingHandler != null) {
        channel.pipeline().addLast(trafficShapingHandler);
    }

    channel.pipeline().addLast(new SocketUpstreamHandler(backendInfo));

    // Keep track of connections per second
    if (connectionsPerSecondTask != null) {
        connectionsPerSecondTask.inc();
    }

    logger.debug("Connected [{}] <-> [{}:{} ({})]",channel.remoteAddress(),backendInfo.getHost(),backendInfo.getPort(),backendInfo.getName());
}

相关文章

买水果
比较全面的redis工具类
gson 反序列化到多态子类
java 版本的 mb_strwidth
JAVA 反转字符串的最快方法,大概比StringBuffer.reverse()性...
com.google.gson.internal.bind.ArrayTypeAdapter的实例源码...