Java Code Examples for org.jboss.netty.channel.Channels

The following examples show how to use org.jboss.netty.channel.Channels. 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 check out the related API usage on the sidebar.
Example 1
Source Project: dubbox   Source File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 2
public ChannelPipeline getPipeline() throws Exception {
	ChannelPipeline pipeline = Channels.pipeline();
	//它负责把字节解码成Http请求。
	pipeline.addLast("decoder", new HttpRequestDecoder());
	//当Server处理完消息后,需要向Client发送响应。那么需要把响应编码成字节,再发送出去。故添加HttpResponseEncoder处理器。
	pipeline.addLast("encoder", new HttpResponseEncoder());
	//它负责把多个HttpMessage组装成一个完整的Http请求或者响应。到底是组装成请求还是响应,则取决于它所处理的内容是请求的内容,还是响应的内容。
	//这其实可以通过Inbound和Outbound来判断,对于Server端而言,在Inbound 端接收请求,在Outbound端返回响应。
	//如果Server向Client返回的数据指定的传输编码是 chunked。则,Server不需要知道发送给Client的数据总长度是多少,它是通过分块发送的,参考分块传输编码
	//pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
	pipeline.addLast("deflater", new HttpContentCompressor());
	//该通道处理器主要是为了处理大文件传输的情形。大文件传输时,需要复杂的状态管理,而ChunkedWriteHandler实现这个功能。
	pipeline.addLast("http-chunked", new ChunkedWriteHandler());
	//自定义的通道处理器,其目的是实现文件服务器的业务逻辑。
	pipeline.addLast("handler", new FileServerHandler());
	return pipeline;
}
 
Example 3
@Override
public ChannelPipeline getPipeline() throws Exception {
    RPCChannelHandler channelHandler = 
            new RPCChannelHandler(syncManager, rpcService);

    IdleStateHandler idleHandler = 
            new IdleStateHandler(timer, 5, 10, 0);
    ReadTimeoutHandler readTimeoutHandler = 
            new ReadTimeoutHandler(timer, 30);
    
    ChannelPipeline pipeline = Channels.pipeline();
    pipeline.addLast("idle", idleHandler);
    pipeline.addLast("timeout", readTimeoutHandler);
    pipeline.addLast("handshaketimeout",
                     new HandshakeTimeoutHandler(channelHandler, timer, 10));

    pipeline.addLast("frameDecoder",
                     new ThriftFrameDecoder(maxFrameSize));
    pipeline.addLast("frameEncoder",
                     new ThriftFrameEncoder());

    pipeline.addLast("handler", channelHandler);
    return pipeline;
}
 
Example 4
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 6 votes vote down vote up
private ServerBootstrap startHttpServer(int port,
    final Token<DelegationTokenIdentifier> token, final URI url) {
  ServerBootstrap bootstrap = new ServerBootstrap(
      new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
          Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(new HttpRequestDecoder(),
          new HttpChunkAggregator(65536), new HttpResponseEncoder(),
          new CredentialsLogicHandler(token, url.toString()));
    }
  });
  bootstrap.bind(new InetSocketAddress("localhost", port));
  return bootstrap;
}
 
Example 5
Source Project: android-netty   Source File: FrameDecoder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Replace this {@link FrameDecoder} in the {@link ChannelPipeline} with the
 * given {@link ChannelHandler}. All remaining bytes in the
 * {@link ChannelBuffer} will get send to the new {@link ChannelHandler}
 * that was used as replacement
 * 
 */
public void replace(String handlerName, ChannelHandler handler) {
	if (ctx == null) {
		throw new IllegalStateException("Replace cann only be called once the FrameDecoder is added to the ChannelPipeline");
	}
	ChannelPipeline pipeline = ctx.getPipeline();
	pipeline.addAfter(ctx.getName(), handlerName, handler);

	try {
		if (cumulation != null) {
			Channels.fireMessageReceived(ctx, cumulation.readBytes(actualReadableBytes()));
		}
	} finally {
		pipeline.remove(this);
	}
}
 
Example 6
Source Project: big-c   Source File: ShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  if (sslFactory != null) {
    pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine()));
  }
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16));
  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("chunking", new ChunkedWriteHandler());
  pipeline.addLast("shuffle", SHUFFLE);
  return pipeline;
  // TODO factor security manager into pipeline
  // TODO factor out encode/decode to permit binary shuffle
  // TODO factor out decode of index to permit alt. models
}
 
Example 7
Source Project: big-c   Source File: SimpleUdpServer.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  // Configure the client.
  DatagramChannelFactory f = new NioDatagramChannelFactory(
      Executors.newCachedThreadPool(), workerCount);

  server = new ConnectionlessBootstrap(f);
  server.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER,
      rpcProgram, RpcUtil.STAGE_RPC_UDP_RESPONSE));

  server.setOption("broadcast", "false");
  server.setOption("sendBufferSize", SEND_BUFFER_SIZE);
  server.setOption("receiveBufferSize", RECEIVE_BUFFER_SIZE);

  // Listen to the UDP port
  ch = server.bind(new InetSocketAddress(port));
  InetSocketAddress socketAddr = (InetSocketAddress) ch.getLocalAddress();
  boundPort = socketAddr.getPort();

  LOG.info("Started listening to UDP requests at port " + boundPort + " for "
      + rpcProgram + " with workerCount " + workerCount);
}
 
Example 8
Source Project: onos   Source File: BgpControllerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
  * Starts the BGP peer.
  *
  * @param connectToSocket the socket to connect to
  */
 private void connect(InetSocketAddress connectToSocket)
     throws InterruptedException {

     ChannelFactory channelFactory =
         new NioClientSocketChannelFactory(
                 Executors.newCachedThreadPool(),
                 Executors.newCachedThreadPool());
     ChannelPipelineFactory pipelineFactory = () -> {
         ChannelPipeline pipeline = Channels.pipeline();
         pipeline.addLast("BgpPeerFrameDecoderTest",
                 peerFrameDecoder);
         pipeline.addLast("BgpPeerChannelHandlerTest",
                 peerChannelHandler);
         return pipeline;
     };

     peerBootstrap = new ClientBootstrap(channelFactory);
     peerBootstrap.setOption("child.keepAlive", true);
     peerBootstrap.setOption("child.tcpNoDelay", true);
     peerBootstrap.setPipelineFactory(pipelineFactory);
     peerBootstrap.connect(connectToSocket);
}
 
Example 9
Source Project: onos   Source File: BgpControllerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
private Channel connectFrom(InetSocketAddress connectToSocket, SocketAddress localAddress)
     throws InterruptedException {

     ChannelFactory channelFactory =
         new NioClientSocketChannelFactory(
                 Executors.newCachedThreadPool(),
                 Executors.newCachedThreadPool());
     ChannelPipelineFactory pipelineFactory = () -> {
         ChannelPipeline pipeline = Channels.pipeline();
         pipeline.addLast("BgpPeerFrameDecoderTest",
                 peerFrameDecoder);
         pipeline.addLast("BgpPeerChannelHandlerTest",
                 peerChannelHandler);
         return pipeline;
     };

     peerBootstrap = new ClientBootstrap(channelFactory);
     peerBootstrap.setOption("child.keepAlive", true);
     peerBootstrap.setOption("child.tcpNoDelay", true);
     peerBootstrap.setPipelineFactory(pipelineFactory);
     Channel channel = peerBootstrap.connect(connectToSocket, localAddress).getChannel();
     return channel;
}
 
Example 10
Source Project: ikasoa   Source File: NettyDispatcher.java    License: MIT License 6 votes vote down vote up
private void writeResponseInOrder(ChannelHandlerContext ctx, TNettyMessage response, int responseSequenceId) {
	synchronized (responseMap) {
		int currentResponseId = lastResponseWrittenId.get() + 1;
		if (responseSequenceId != currentResponseId)
			responseMap.put(responseSequenceId, response);
		else {
			// 写入下一行的response.
			do {
				Channels.write(ctx.getChannel(), response);
				lastResponseWrittenId.incrementAndGet();
				++currentResponseId;
				response = responseMap.remove(currentResponseId);
			} while (null != response);
			if (DispatcherContext.isChannelReadBlocked(ctx)
					&& dispatcherSequenceId.get() <= lastResponseWrittenId.get() + queuedResponseLimit)
				DispatcherContext.unblockChannelReads(ctx);
		}
	}
}
 
Example 11
Source Project: ikasoa   Source File: ThriftFrameDecoder.java    License: MIT License 6 votes vote down vote up
protected ChannelBuffer tryDecodeFramedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer,
		boolean stripFraming) {

	int messageStartReaderIndex = buffer.readerIndex();
	int messageContentsOffset = stripFraming ? messageStartReaderIndex + MESSAGE_FRAME_SIZE
			: messageStartReaderIndex;
	int messageLength = buffer.getInt(messageStartReaderIndex) + MESSAGE_FRAME_SIZE;
	int messageContentsLength = messageStartReaderIndex + messageLength - messageContentsOffset;

	if (messageContentsLength > maxFrameSize)
		Channels.fireExceptionCaught(ctx,
				new TooLongFrameException(String.format("Maximum frame size of %d exceeded .", maxFrameSize)));

	if (messageLength == 0) {
		buffer.readerIndex(messageContentsOffset);
		return null;
	} else if (buffer.readableBytes() < messageLength)
		return null;
	else {
		ChannelBuffer messageBuffer = extractFrame(buffer, messageContentsOffset, messageContentsLength);
		buffer.readerIndex(messageStartReaderIndex + messageLength);
		return messageBuffer;
	}
}
 
Example 12
Source Project: dubbox   Source File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new ClientBootstrap(channelFactory);
    // config
    // @see org.jboss.netty.channel.socket.SocketChannelConfig
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("connectTimeoutMillis", getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline pipeline = Channels.pipeline();
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
}
 
Example 13
Source Project: anima   Source File: NettyClient.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doOpen() throws Throwable {
	bootstrap = new ClientBootstrap(channelFactory);
	bootstrap.setOption("keepAlive", true);
	bootstrap.setOption("tcpNoDelay", true);
	bootstrap.setOption("connectTimeoutMillis", getConnectTimeout());
	final NettyHandler nettyHandler = new NettyHandler(getConf(), this);
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() {
			NettyCodecAdapter adapter = new NettyCodecAdapter(getConf(),getCodec(), NettyClient.this);
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("decoder", adapter.getDecoder());
			pipeline.addLast("encoder", adapter.getEncoder());
			pipeline.addLast("handler", nettyHandler);
			return pipeline;
		}
	});
}
 
Example 14
@Override
public ChannelPipeline getPipeline() throws Exception {
    BootstrapChannelHandler handler = 
            new BootstrapChannelHandler(bootstrap);
    ChannelPipeline pipeline = Channels.pipeline();

    pipeline.addLast("frameDecoder",
                     new ThriftFrameDecoder(maxFrameSize));
    pipeline.addLast("frameEncoder",
                     new ThriftFrameEncoder());
    pipeline.addLast("timeout",
                     new BootstrapTimeoutHandler(timer, 10));

    pipeline.addLast("handler", handler);

    return pipeline;
}
 
Example 15
@Override
public ChannelPipeline getPipeline() throws Exception {
    RemoteSyncChannelHandler channelHandler = 
            new RemoteSyncChannelHandler(syncManager);
    ChannelPipeline pipeline = Channels.pipeline();

    pipeline.addLast("frameDecoder",
                     new ThriftFrameDecoder(maxFrameSize));
    pipeline.addLast("frameEncoder",
                     new ThriftFrameEncoder());
    pipeline.addLast("timeout",
                     new RSHandshakeTimeoutHandler(channelHandler,
                                                   timer, 3));

    pipeline.addLast("handler", channelHandler);
    return pipeline;
}
 
Example 16
Source Project: Flink-CEPplus   Source File: NetworkFailuresProxy.java    License: Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

	// Set up the event pipeline factory.
	ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(executor, executor);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();

			// synchronized for a race between blocking and creating new handlers
			synchronized (networkFailureHandlers) {
				NetworkFailureHandler failureHandler = new NetworkFailureHandler(
					blocked,
					networkFailureHandler -> networkFailureHandlers.remove(networkFailureHandler),
					channelFactory,
					remoteHost,
					remotePort);
				networkFailureHandlers.add(failureHandler);
				pipeline.addLast(NETWORK_FAILURE_HANDLER_NAME, failureHandler);
			}
			return pipeline;
		}
	});
	channel = serverBootstrap.bind(new InetSocketAddress(localPort));

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example 17
Source Project: flink   Source File: NetworkFailuresProxy.java    License: Apache License 2.0 5 votes vote down vote up
public NetworkFailuresProxy(int localPort, String remoteHost, int remotePort) {
	// Configure the bootstrap.
	serverBootstrap = new ServerBootstrap(
		new NioServerSocketChannelFactory(executor, executor));

	// Set up the event pipeline factory.
	ClientSocketChannelFactory channelFactory = new NioClientSocketChannelFactory(executor, executor);
	serverBootstrap.setOption("child.tcpNoDelay", true);
	serverBootstrap.setOption("child.keepAlive", true);
	serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();

			// synchronized for a race between blocking and creating new handlers
			synchronized (networkFailureHandlers) {
				NetworkFailureHandler failureHandler = new NetworkFailureHandler(
					blocked,
					networkFailureHandler -> networkFailureHandlers.remove(networkFailureHandler),
					channelFactory,
					remoteHost,
					remotePort);
				networkFailureHandlers.add(failureHandler);
				pipeline.addLast(NETWORK_FAILURE_HANDLER_NAME, failureHandler);
			}
			return pipeline;
		}
	});
	channel = serverBootstrap.bind(new InetSocketAddress(localPort));

	LOG.info("Proxying [*:{}] to [{}:{}]", getLocalPort(), remoteHost, remotePort);
}
 
Example 18
Source Project: canal-1.1.3   Source File: NettyUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void write(Channel channel, ByteBuffer body, ChannelFutureListener channelFutureListner) {
    byte[] header = ByteBuffer.allocate(HEADER_LENGTH).order(ByteOrder.BIG_ENDIAN).putInt(body.limit()).array();
    List<ChannelBuffer> components = new ArrayList<ChannelBuffer>(2);
    components.add(ChannelBuffers.wrappedBuffer(ByteOrder.BIG_ENDIAN, header));
    components.add(ChannelBuffers.wrappedBuffer(body));

    if (channelFutureListner == null) {
        Channels.write(channel, new CompositeChannelBuffer(ByteOrder.BIG_ENDIAN, components));
    } else {
        Channels.write(channel, new CompositeChannelBuffer(ByteOrder.BIG_ENDIAN, components))
            .addListener(channelFutureListner);
    }
}
 
Example 19
Source Project: fqueue   Source File: MemcachedCommandHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void handleAppend(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command,
		Channel channel) throws DatabaseException, Exception {
	Cache.StoreResponse ret;
	ret = cache.append(command.element);
	Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel
			.getRemoteAddress());
}
 
Example 20
Source Project: incubator-tajo   Source File: ProtoPipelineFactory.java    License: Apache License 2.0 5 votes vote down vote up
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline p = Channels.pipeline();
  p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576*2, 0, 4,
      0, 4));
  p.addLast("protobufDecoder", new ProtobufDecoder(defaultInstance));
  p.addLast("frameEncoder", new LengthFieldPrepender(4));
  p.addLast("protobufEncoder", new ProtobufEncoder());
  p.addLast("handler", handler);
  return p;
}
 
Example 21
Source Project: RDFS   Source File: TaskTracker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  return Channels.pipeline(
    new HttpRequestDecoder(),
    new HttpChunkAggregator(1 << 16),
    new HttpResponseEncoder(),
    new ChunkedWriteHandler(),
    shuffleHandler);
}
 
Example 22
Source Project: feeyo-hlsserver   Source File: UdpClient.java    License: Apache License 2.0 5 votes vote down vote up
public UdpClient(final UdpClientChannelHandler channelHandler) {
	
	bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory());
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("handler", channelHandler);
			return pipeline;
		}
	});
	
	bootstrap.setOption("localAddress", new InetSocketAddress(10002));
	channel = bootstrap.bind();
}
 
Example 23
Source Project: voyage   Source File: RpcRequestEncode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	RpcRequest request = (RpcRequest) e.getMessage();
	ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
	//先写入标示的魔数
	baos.write(Constants.MAGIC_BYTES);
	MySerializerFactory.getInstance(Constants.DEFAULT_RPC_CODE_MODE).encodeRequest(baos, request);
	ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(baos.toByteArray());
	Channels.write(ctx, e.getFuture(), buffer);
}
 
Example 24
Source Project: onos   Source File: BgpSessionManager.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
    log.debug("BGP Session Manager start.");
    isShutdown = false;

    ChannelFactory channelFactory = new NioServerSocketChannelFactory(
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-boss-%d", log)),
            newCachedThreadPool(groupedThreads("onos/bgp", "sm-worker-%d", log)));
    ChannelPipelineFactory pipelineFactory = () -> {
        // Allocate a new session per connection
        BgpSession bgpSessionHandler =
                new BgpSession(BgpSessionManager.this);
        BgpFrameDecoder bgpFrameDecoder =
                new BgpFrameDecoder(bgpSessionHandler);

        // Setup the processing pipeline
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("BgpFrameDecoder", bgpFrameDecoder);
        pipeline.addLast("BgpSession", bgpSessionHandler);
        return pipeline;
    };
    InetSocketAddress listenAddress =
            new InetSocketAddress(bgpPort);

    serverBootstrap = new ServerBootstrap(channelFactory);
    // serverBootstrap.setOptions("reuseAddr", true);
    serverBootstrap.setOption("child.keepAlive", true);
    serverBootstrap.setOption("child.tcpNoDelay", true);
    serverBootstrap.setPipelineFactory(pipelineFactory);
    try {
        serverChannel = serverBootstrap.bind(listenAddress);
        allChannels.add(serverChannel);
    } catch (ChannelException e) {
        log.debug("Exception binding to BGP port {}: ",
                  listenAddress.getPort(), e);
    }
}
 
Example 25
Source Project: voyage   Source File: NettyRpcConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * @param connectStatus 心跳检测状态是否正常
	 * @throws Throwable
	 */
	public void open(boolean connectStatus) throws Throwable {
		logger.info("open start,"+getConnStr());
		bootstrap = new ClientBootstrap(factory);
//		timer = new HashedWheelTimer();
		{
			bootstrap.setOption("tcpNoDelay", Boolean.parseBoolean(clientConfig.getTcpNoDelay()));
			bootstrap.setOption("reuseAddress", Boolean.parseBoolean(clientConfig.getReuseAddress()));
			bootstrap.setOption("SO_RCVBUF",1024*128);
			bootstrap.setOption("SO_SNDBUF",1024*128);
			bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
				public ChannelPipeline getPipeline() {
					ChannelPipeline pipeline = Channels.pipeline();
//					int readTimeout = clientConfig.getReadTimeout();
//					if (readTimeout > 0) {
//						pipeline.addLast("timeout", new ReadTimeoutHandler(timer,
//								readTimeout, TimeUnit.MILLISECONDS));
//					}
					pipeline.addLast("encoder", new RpcRequestEncode());
					pipeline.addLast("decoder", new RpcResponseDecode());
					pipeline.addLast("handler", NettyRpcConnection.this);
					return pipeline;
				}
			});
		}
		connected.set(connectStatus);
		logger.info("open finish,"+getConnStr());
	}
 
Example 26
Source Project: onos   Source File: IsisPipelineFactory.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    ChannelPipeline pipeline = Channels.pipeline();
    pipeline.addLast("encoder", new IsisMessageDecoder());
    pipeline.addLast("decoder", new IsisMessageEncoder());
    pipeline.addLast("handler", isisChannelHandler);

    return pipeline;
}
 
Example 27
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }

    if (!ctx.getChannel().isOpen()) {
        return;
    }
    if (!channelHandler.isHandshakeComplete())
        Channels.fireExceptionCaught(ctx, EXCEPTION);
}
 
Example 28
Source Project: dubbox   Source File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example 29
public ChannelPipeline getPipeline() throws Exception {
	ChannelPipeline pipeline = Channels.pipeline();
	this.clientHandler = new FileClientHandler();
	pipeline.addLast("codec", new HttpClientCodec());
	pipeline.addLast("inflater", new HttpContentDecompressor());
	pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
	pipeline.addLast("handler", this.clientHandler); //具体文件处理句柄
	return pipeline;
}
 
Example 30
Source Project: mt-flume   Source File: RpcTestUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
  ChannelPipeline pipeline = Channels.pipeline();
  ZlibEncoder encoder = new ZlibEncoder(6);
  pipeline.addFirst("deflater", encoder);
  pipeline.addFirst("inflater", new ZlibDecoder());
  return pipeline;
}