io.netty.handler.codec.LengthFieldPrepender Java Examples

The following examples show how to use io.netty.handler.codec.LengthFieldPrepender. 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: LengthFieldPrependerTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrependLengthInLittleEndian() throws Exception {
    final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(ByteOrder.LITTLE_ENDIAN, 4, 0, false));
    ch.writeOutbound(msg);
    ByteBuf buf = ch.readOutbound();
    assertEquals(4, buf.readableBytes());
    byte[] writtenBytes = new byte[buf.readableBytes()];
    buf.getBytes(0, writtenBytes);
    assertEquals(1, writtenBytes[0]);
    assertEquals(0, writtenBytes[1]);
    assertEquals(0, writtenBytes[2]);
    assertEquals(0, writtenBytes[3]);
    buf.release();

    buf = ch.readOutbound();
    assertSame(buf, msg);
    buf.release();
    assertFalse("The channel must have been completely read", ch.finish());
}
 
Example #2
Source File: EppModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * {@link Provides} the list of providers of {@link ChannelHandler}s that are used for the EPP
 * Protocol.
 */
@Provides
@EppProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideEppHandlerProviders(
    @EppProtocol Provider<SslClientInitializer<NioSocketChannel>> sslClientInitializerProvider,
    Provider<LengthFieldBasedFrameDecoder> lengthFieldBasedFrameDecoderProvider,
    Provider<LengthFieldPrepender> lengthFieldPrependerProvider,
    Provider<EppMessageHandler> eppMessageHandlerProvider,
    Provider<EppActionHandler> eppActionHandlerProvider) {
  return ImmutableList.of(
      sslClientInitializerProvider,
      lengthFieldBasedFrameDecoderProvider,
      lengthFieldPrependerProvider,
      eppMessageHandlerProvider,
      eppActionHandlerProvider);
}
 
Example #3
Source File: TcpServer.java    From krpc with MIT License 6 votes vote down vote up
protected static void run() throws Exception {
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup);
		b.channel(NioServerSocketChannel.class);
		b.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
				pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
				pipeline.addLast("decoder", new ByteArrayDecoder());
				pipeline.addLast("encoder", new ByteArrayEncoder());
//				pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//				pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
				pipeline.addLast(new TcpServerHandler());
			}
		});

		// b.bind(IP, PORT).sync();
		ChannelFuture f = b.bind(PORT).sync(); // (7)

		f.channel().closeFuture().sync();

		System.out.println("TCP服务器已启动");
	}
 
Example #4
Source File: TCPClient.java    From krpc with MIT License 6 votes vote down vote up
/**
 * 初始化Bootstrap
 * 
 * @return
 */
public static final Bootstrap getBootstrap() {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();
	b.group(group).channel(NioSocketChannel.class);
	b.handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();
			pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
			pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
			pipeline.addLast("decoder", new ByteArrayDecoder());
			pipeline.addLast("encoder", new ByteArrayEncoder());
			pipeline.addLast("handler", new TcpClientHandler());
		}
	});
	return b;
}
 
Example #5
Source File: EppProtocolModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@EppProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
    Provider<ProxyProtocolHandler> proxyProtocolHandlerProvider,
    @EppProtocol Provider<SslServerInitializer<NioSocketChannel>> sslServerInitializerProvider,
    @EppProtocol Provider<ReadTimeoutHandler> readTimeoutHandlerProvider,
    Provider<LengthFieldBasedFrameDecoder> lengthFieldBasedFrameDecoderProvider,
    Provider<LengthFieldPrepender> lengthFieldPrependerProvider,
    Provider<EppServiceHandler> eppServiceHandlerProvider,
    Provider<FrontendMetricsHandler> frontendMetricsHandlerProvider,
    Provider<EppQuotaHandler> eppQuotaHandlerProvider,
    Provider<FullHttpRequestRelayHandler> relayHandlerProvider) {
  return ImmutableList.of(
      proxyProtocolHandlerProvider,
      sslServerInitializerProvider,
      readTimeoutHandlerProvider,
      lengthFieldBasedFrameDecoderProvider,
      lengthFieldPrependerProvider,
      eppServiceHandlerProvider,
      frontendMetricsHandlerProvider,
      eppQuotaHandlerProvider,
      relayHandlerProvider);
}
 
Example #6
Source File: TCPClient.java    From krpc with MIT License 6 votes vote down vote up
/**
 * 初始化Bootstrap
 * 
 * @return
 */
public  Bootstrap getBootstrap() {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();
	b.group(group).channel(NioSocketChannel.class);
	TcpClientHandler tcpClientHandler = new TcpClientHandler(TCPClient.this);
	b.handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel ch) throws Exception {
			ChannelPipeline pipeline = ch.pipeline();
			pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
			pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
			pipeline.addLast("decoder", new ByteArrayDecoder());
			pipeline.addLast("encoder", new ByteArrayEncoder());
			pipeline.addLast("handler", tcpClientHandler);
		}
	});
	return b;
}
 
Example #7
Source File: NetworkServiceImpl.java    From ServerCore with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) {
    ChannelPipeline pip = ch.pipeline();
    int maxLength = 1048576;
    int lengthFieldLength = 4;
    int ignoreLength = -4;
    int offset = 0;
    pip.addLast(new LengthFieldBasedFrameDecoder(maxLength, offset, lengthFieldLength, ignoreLength, lengthFieldLength));
    pip.addLast(new MessageDecoder(builder.getImessageandhandler()));
    pip.addLast(new LengthFieldPrepender(4, true));
    pip.addLast(new MessageEncoder(builder.getImessageandhandler()));
    pip.addLast(new MessageExecutor(builder.getConsumer(), builder.getListener()));
    for (ChannelHandler handler : builder.getExtraHandlers()) {
        pip.addLast(handler);
    }
}
 
Example #8
Source File: NettyTransportClient.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private Bootstrap initClientBootstrap() {
    Bootstrap b = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    b.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClusterClientConfigManager.getConnectTimeout())
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                clientHandler = new TokenClientHandler(currentState, disconnectCallback);

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
                pipeline.addLast(new NettyResponseDecoder());
                pipeline.addLast(new LengthFieldPrepender(2));
                pipeline.addLast(new NettyRequestEncoder());
                pipeline.addLast(clientHandler);
            }
        });

    return b;
}
 
Example #9
Source File: ClientInitializer.java    From Summer with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel sc) {
	ChannelPipeline pipeline = sc.pipeline();
	ClientConfig config = clientContext.getConfig();
	if (ServerConst.SERVER_PROTOCOL_STRING_LINE.equals(config.getProtocol())) {
		pipeline.addLast(new StringPasswordLineDecoder(config.getMsgLength(), config.getCharset(), config.getPassword()));
		pipeline.addLast(new StringPasswordLineEncoder(config.getCharset(), config.getPassword()));
	} else if (ServerConst.SERVER_PROTOCOL_LENGTH_FIELD.equals(config.getProtocol())) {
		pipeline.addLast(new LengthFieldBasedFrameDecoder(config.getMsgLength(), 0, 4, 0, 4));
		pipeline.addLast(new LengthFieldPrepender(4));
		pipeline.addLast(new StringPasswordDecoder(config.getCharset(), config.getPassword()));
		pipeline.addLast(new StringPasswordEncoder(config.getCharset(), config.getPassword()));
	} else {
		throw new NotFoundProtocolException(config.getProtocol());
	}
	pipeline.addLast(new ClientStringHandler(clientContext));
}
 
Example #10
Source File: NettyRpcClientChannelInitializer.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 ObjectSerializerEncoder());
    ch.pipeline().addLast(new ObjectSerializerDecoder());


    ch.pipeline().addLast(rpcCmdDecoder);
    ch.pipeline().addLast(new RpcCmdEncoder());
    ch.pipeline().addLast(nettyClientRetryHandler);
    ch.pipeline().addLast(socketManagerInitHandler);
    ch.pipeline().addLast(rpcAnswerHandler);
}
 
Example #11
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 #12
Source File: LengthFieldPrependerTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrependLengthInLittleEndian() throws Exception {
    final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(ByteOrder.LITTLE_ENDIAN, 4, 0, false));
    ch.writeOutbound(msg);
    ByteBuf buf = (ByteBuf) ch.readOutbound();
    assertEquals(5, buf.readableBytes());
    byte[] writtenBytes = new byte[buf.readableBytes()];
    buf.getBytes(0, writtenBytes);
    assertEquals(1, writtenBytes[0]);
    assertEquals(0, writtenBytes[1]);
    assertEquals(0, writtenBytes[2]);
    assertEquals(0, writtenBytes[3]);
    assertEquals('A', writtenBytes[4]);
    buf.release();
    assertFalse("The channel must have been completely read", ch.finish());
}
 
Example #13
Source File: NodeServerBootstrap.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
@PostConstruct
public void start() throws Exception {

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup)
            .channelFactory(NioServerSocketChannel::new)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));
                    pipeline.addLast("handler", nodeChannelInBoundHandler);
                }
            })
            .option(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_SNDBUF, 2048)
            .option(ChannelOption.SO_RCVBUF, 1024);
    bootstrap.bind(goPushNodeServerConfig.getNodePort()).sync();
    log.info("Node server start successful! listening port: {}", goPushNodeServerConfig.getNodePort());
}
 
Example #14
Source File: NettyTransport.java    From jzab with Apache License 2.0 6 votes vote down vote up
public Sender(final String source, final String destination) {
  this.destination = destination;
  bootstrap = new Bootstrap();
  bootstrap.group(workerGroup);
  bootstrap.channel(NioSocketChannel.class);
  bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
  bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
  bootstrap.option(ChannelOption.TCP_NODELAY, true);
  bootstrap.handler(new ChannelInitializer<SocketChannel>() {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
      if (isSslEnabled()) {
        SSLEngine engine = serverContext.createSSLEngine();
        engine.setUseClientMode(true);
        ch.pipeline().addLast(new SslHandler(engine));
      }
      // Inbound handlers.
      ch.pipeline().addLast("clientError", new ClientErrorHandler());
      // Outbound handlers.
      ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
    }
  });
}
 
Example #15
Source File: NettyTransportClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private Bootstrap initClientBootstrap() {
    Bootstrap b = new Bootstrap();
    eventLoopGroup = new NioEventLoopGroup();
    b.group(eventLoopGroup)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ClusterClientConfigManager.getConnectTimeout())
        .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                clientHandler = new TokenClientHandler(currentState, disconnectCallback);

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2));
                pipeline.addLast(new NettyResponseDecoder());
                pipeline.addLast(new LengthFieldPrepender(2));
                pipeline.addLast(new NettyRequestEncoder());
                pipeline.addLast(clientHandler);
            }
        });

    return b;
}
 
Example #16
Source File: TCPChannelInitializerHandler.java    From NettyChat with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
    ChannelPipeline pipeline = channel.pipeline();

    // netty提供的自定义长度解码器,解决TCP拆包/粘包问题
    pipeline.addLast("frameEncoder", new LengthFieldPrepender(2));
    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535,
            0, 2, 0, 2));

    // 增加protobuf编解码支持
    pipeline.addLast(new ProtobufEncoder());
    pipeline.addLast(new ProtobufDecoder(MessageProtobuf.Msg.getDefaultInstance()));

    // 握手认证消息响应处理handler
    pipeline.addLast(LoginAuthRespHandler.class.getSimpleName(), new LoginAuthRespHandler(imsClient));
    // 心跳消息响应处理handler
    pipeline.addLast(HeartbeatRespHandler.class.getSimpleName(), new HeartbeatRespHandler(imsClient));
    // 接收消息处理handler
    pipeline.addLast(TCPReadHandler.class.getSimpleName(), new TCPReadHandler(imsClient));
}
 
Example #17
Source File: QueryServer.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public void start() {
  _bossGroup = new NioEventLoopGroup();
  _workerGroup = new NioEventLoopGroup();
  try {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    _channel = serverBootstrap.group(_bossGroup, _workerGroup).channel(NioServerSocketChannel.class)
        .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
        .childHandler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ch.pipeline()
                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, Integer.BYTES, 0, Integer.BYTES),
                    new LengthFieldPrepender(Integer.BYTES),
                    new InstanceRequestHandler(_queryScheduler, _serverMetrics));
          }
        }).bind(_port).sync().channel();
  } catch (Exception e) {
    // Shut down immediately
    _workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
    _bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
    throw new RuntimeException(e);
  }
}
 
Example #18
Source File: ServerChannels.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
ServerChannel(ServerRoutingInstance serverRoutingInstance) {
  _serverRoutingInstance = serverRoutingInstance;
  _bootstrap = new Bootstrap().remoteAddress(serverRoutingInstance.getHostname(), serverRoutingInstance.getPort())
      .group(_eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
      .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) {
          ch.pipeline()
              .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, Integer.BYTES, 0, Integer.BYTES),
                  new LengthFieldPrepender(Integer.BYTES),
                  // NOTE: data table de-serialization happens inside this handler
                  // Revisit if this becomes a bottleneck
                  new DataTableHandler(_queryRouter, _serverRoutingInstance, _brokerMetrics));
        }
      });
}
 
Example #19
Source File: Client.java    From push with Apache License 2.0 6 votes vote down vote up
public void run() {
    workerGroup = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        // b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new MsgPackDecode());
                pipeline.addLast("encoder", new MsgPackEncode());
                pipeline.addLast(ClientConfiguration.clientHandler());
            }
        });
        channel = b.connect(clientProperties.getServerHost(), clientProperties.getServerPort()).sync().channel();
        status = Status.START;
        channel.closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
    status = Status.STOP;
}
 
Example #20
Source File: LengthFieldPrependerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrependLength() throws Exception {
    final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(4));
    ch.writeOutbound(msg);
    final ByteBuf buf = (ByteBuf) ch.readOutbound();
    assertThat(buf, is(wrappedBuffer(new byte[]{0, 0, 0, 1, 'A'})));
    buf.release();
}
 
Example #21
Source File: DeviceServerBootstrap.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
@PostConstruct
public void start() throws Exception {


    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workGroup)
            .channelFactory(NioServerSocketChannel::new)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast("logHandler", new LoggingHandler());
                    pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                    pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
                    pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                    pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
                    pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));

                    pipeline.addLast("handler", deviceChannelInboundHandler);
                }
            })

            .option(ChannelOption.SO_BACKLOG, 1000000)  //连接队列深度
            .option(ChannelOption.TCP_NODELAY, true)   //设置 no_delay
            .option(ChannelOption.SO_SNDBUF, 2048).option(ChannelOption.SO_RCVBUF, 1024)
            .childOption(ChannelOption.TCP_NODELAY, true)
            .childOption(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.SO_SNDBUF, 2048).childOption(ChannelOption.SO_RCVBUF, 1024)
            .childOption(ChannelOption.SO_LINGER, 0);

    bootstrap.bind(goPushNodeServerConfig.getDevicePort()).sync();
    log.info("device server start successful! listening port: {}", goPushNodeServerConfig.getDevicePort());
}
 
Example #22
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 #23
Source File: EppProtocolModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Singleton
@Provides
static LengthFieldPrepender provideLengthFieldPrepender(ProxyConfig config) {
  return new LengthFieldPrepender(
      // Header field length.
      config.epp.headerLengthBytes,
      // Length includes header field length.
      true);
}
 
Example #24
Source File: Node.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
private ChannelInitializer channelInitializer() {
    return new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            ChannelPipeline pipeline = socketChannel.pipeline();
            pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
            pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0));
            pipeline.addLast("handler", nodeChannelInBoundHandler());
        }
    };
}
 
Example #25
Source File: LengthFieldPrependerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrependLengthIncludesLengthFieldLength() throws Exception {
    final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(4, true));
    ch.writeOutbound(msg);
    final ByteBuf buf = (ByteBuf) ch.readOutbound();
    assertThat(buf, is(wrappedBuffer(new byte[]{0, 0, 0, 5, 'A'})));
    buf.release();
}
 
Example #26
Source File: LengthFieldPrependerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrependAdjustedLength() throws Exception {
    final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(4, -1));
    ch.writeOutbound(msg);
    final ByteBuf buf = (ByteBuf) ch.readOutbound();
    assertThat(buf, is(wrappedBuffer(new byte[]{0, 0, 0, 0, 'A'})));
    buf.release();
}
 
Example #27
Source File: LengthFieldPrependerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdjustedLengthLessThanZero() throws Exception {
    final EmbeddedChannel ch = new EmbeddedChannel(new LengthFieldPrepender(4, -2));
    try {
        ch.writeOutbound(msg);
        fail(EncoderException.class.getSimpleName() + " must be raised.");
    } catch (EncoderException e) {
        // Expected
    }
}
 
Example #28
Source File: PlacementServer.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelHandler newChannelInitializer() {
    return new ChannelInitializer<NioSocketChannel>() {
        @Override
        protected void initChannel(NioSocketChannel ch) throws Exception {
            ChannelPipeline cp = ch.pipeline();
            cp.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2));
            cp.addLast("prepender", new LengthFieldPrepender(2, false));
            // Any other useful handler
            cp.addLast("strDecoder", STRING_DECODER);
            cp.addLast("strEncoder", STRING_ENCODER);
            cp.addLast("handler", new DisruptorAdapterBy41xHandler<JsonRequest>() {
                protected Executor newExecutor(Session session, JsonRequest msg) {
                    return new Executor() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void onExecute() {
                            try {
                                Command command = serviceManager.getCommand(msg.getApi());
                                if (command == null) {
                                    LOG.warn("Command is not exist. API : ", msg.getApi());
                                    return;
                                }
                                command.execute(session, msg);
                            } catch (Exception e) {
                                LOG.error("Error occured by execute command.", e);
                            }
                        }

                        @Override
                        public void release() {

                        }
                    };
                }
            });
        }
    };
}
 
Example #29
Source File: NettyChannelInitializer.java    From reef with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(final SocketChannel ch) throws Exception {
  ch.pipeline()
      .addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAXFRAMELENGTH, 0, 4, 0, 4))
      .addLast("bytesDecoder", new ByteArrayDecoder())
      .addLast("frameEncoder", new LengthFieldPrepender(4))
      .addLast("bytesEncoder", new ByteArrayEncoder())
      .addLast("chunker", new ChunkedReadWriteHandler())
      .addLast("handler", handlerFactory.createChannelInboundHandler());
}
 
Example #30
Source File: OlapPipelineFactory.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
    SpliceLogUtils.trace(LOG, "Creating new channel pipeline...");
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(1<<30,0,4,0,4)); //max frame size is 1GB=2^30 bytes
    pipeline.addLast("protobufDecoder",decoder);
    pipeline.addLast("frameEncoder",new LengthFieldPrepender(4));
    pipeline.addLast("protobufEncoder",new ProtobufEncoder());
    pipeline.addLast("statusHandler", statusHandler);
    pipeline.addLast("submitHandler", submitHandler);
    pipeline.addLast("cancelHandler",cancelHandler);
    SpliceLogUtils.trace(LOG, "Done creating channel pipeline");
}