io.netty.channel.ChannelPipeline Java Examples

The following examples show how to use io.netty.channel.ChannelPipeline. 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: SecureChatServerInitializer.java    From netty-4.1.22 with Apache License 2.0 7 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example #2
Source File: AbstractEpollStreamChannel.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private boolean handleReadException(ChannelPipeline pipeline, ByteBuf byteBuf, Throwable cause, boolean close) {
    if (byteBuf != null) {
        if (byteBuf.isReadable()) {
            readPending = false;
            pipeline.fireChannelRead(byteBuf);
        } else {
            byteBuf.release();
        }
    }
    pipeline.fireChannelReadComplete();
    pipeline.fireExceptionCaught(cause);
    if (close || cause instanceof IOException) {
        closeOnRead(pipeline);
        return true;
    }
    return false;
}
 
Example #3
Source File: EchoFromClientIT.java    From jreactive-8583 with Apache License 2.0 6 votes vote down vote up
@Override
protected void configureServer(Iso8583Server<IsoMessage> server) {
    server.setConfigurer(new ConnectorConfigurer<>() {

        @Override
        public void configurePipeline(ChannelPipeline pipeline, ServerConfiguration configuration) {
            pipeline.addBefore("idleEventHandler", "connectListenerHandler", new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    super.channelActive(ctx);
                    final IsoMessage message = server.getIsoMessageFactory().newMessage(0x800);
                    ctx.writeAndFlush(message);
                }
            });
        }
    });
}
 
Example #4
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeServer(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.addFirst(new EncapsulatedHandshakeSender(null, false));
	NetworkDataCache cache = NetworkDataCache.getFrom(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromServerPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToServerPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener(handler -> {
		try {
			return (handler instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example #5
Source File: TestString.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
private void createChannel(int port) throws InterruptedException {
    ServerBootstrap b = new ServerBootstrap();
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(2);
    b.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new LoggingHandler(LogLevel.DEBUG));
                    p.addLast(new NettySimpleMessageHandler());
                    p.addLast(new NettyMasterHandler(null, new CommandHandlerManager(), 1000 * 60 * 24));
                    p.addLast(new HAProxyMessageDecoder());
                }
            });
    b.bind(port).sync();
}
 
Example #6
Source File: ProxyServer.java    From karate with MIT License 6 votes vote down vote up
public ProxyServer(int requestedPort, RequestFilter requestFilter, ResponseFilter responseFilter) {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup(8);
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel c) {
                        ChannelPipeline p = c.pipeline();
                        p.addLast(new HttpServerCodec());
                        p.addLast(new HttpObjectAggregator(1048576));
                        p.addLast(new ProxyClientHandler(requestFilter, responseFilter));
                    }
                });
        channel = b.bind(requestedPort).sync().channel();
        InetSocketAddress isa = (InetSocketAddress) channel.localAddress();
        String host = "127.0.0.1"; //isa.getHostString();
        port = isa.getPort();
        logger.info("proxy server started - http://{}:{}", host, port);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: SpigotServerConnectionChannel.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void initChannel(Channel channel) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkManagerWrapper networkmanager = new SpigotNetworkManagerWrapper(channel, (NetworkManager) pipeline.get(SpigotChannelHandlers.NETWORK_MANAGER));
	networkmanager.setPacketListener(new SpigotFakePacketListener(networkmanager));
	ConnectionImpl connection = new ConnectionImpl(networkmanager);
	ProtocolStorage.addConnection(channel.remoteAddress(), connection);
	pipeline.addAfter(SpigotChannelHandlers.READ_TIMEOUT, ChannelHandlers.INITIAL_DECODER, new InitialPacketDecoder());
	pipeline.addBefore(SpigotChannelHandlers.NETWORK_MANAGER, ChannelHandlers.LOGIC, new LogicHandler(connection, Packet.class));
	pipeline.remove("legacy_query");
	pipeline.replace(SpigotChannelHandlers.READ_TIMEOUT, SpigotChannelHandlers.READ_TIMEOUT, new SimpleReadTimeoutHandler(30));
	pipeline.replace(SpigotChannelHandlers.SPLITTER, SpigotChannelHandlers.SPLITTER, new SpigotWrappedSplitter());
	pipeline.replace(SpigotChannelHandlers.PREPENDER, SpigotChannelHandlers.PREPENDER, new SpigotWrappedPrepender());
	pipeline.addAfter(SpigotChannelHandlers.PREPENDER, ChannelHandlers.RAW_CAPTURE_SEND, new RawPacketDataCaptureSend(connection));
	pipeline.addAfter(SpigotChannelHandlers.SPLITTER, ChannelHandlers.RAW_CAPTURE_RECEIVE, new RawPacketDataCaptureReceive(connection));
	if (replaceDecoderEncoder) {
		if (pipeline.get(SpigotChannelHandlers.DECODER).getClass().equals(net.minecraft.server.v1_16_R1.PacketDecoder.class)) {
			pipeline.replace(SpigotChannelHandlers.DECODER, SpigotChannelHandlers.DECODER, new SpigotPacketDecoder());
		}
		if (pipeline.get(SpigotChannelHandlers.ENCODER).getClass().equals(net.minecraft.server.v1_16_R1.PacketEncoder.class)) {
			pipeline.replace(SpigotChannelHandlers.ENCODER, SpigotChannelHandlers.ENCODER, new SpigotPacketEncoder());
		}
	}
}
 
Example #8
Source File: NettyPipelineInit.java    From Lottor with MIT License 6 votes vote down vote up
public static void serializePipeline(SerializeProtocolEnum serializeProtocol, ChannelPipeline pipeline) {
    switch (serializeProtocol) {
        case KRYO:
            KryoCodecServiceImpl kryoCodecServiceImpl = new KryoCodecServiceImpl(KryoPoolFactory.getKryoPoolInstance());
            pipeline.addLast(new KryoEncoder(kryoCodecServiceImpl));
            pipeline.addLast(new KryoDecoder(kryoCodecServiceImpl));
            break;
        case HESSIAN:
            HessianCodecServiceImpl hessianCodecServiceImpl = new HessianCodecServiceImpl();
            pipeline.addLast(new HessianEncoder(hessianCodecServiceImpl));
            pipeline.addLast(new HessianDecoder(hessianCodecServiceImpl));
            break;
        case PROTOSTUFF:
            ProtostuffCodecServiceImpl protostuffCodecServiceImpl = new ProtostuffCodecServiceImpl();
            pipeline.addLast(new ProtostuffEncoder(protostuffCodecServiceImpl));
            pipeline.addLast(new ProtostuffDecoder(protostuffCodecServiceImpl));
            break;
        default:
            KryoCodecServiceImpl defaultCodec = new KryoCodecServiceImpl(KryoPoolFactory.getKryoPoolInstance());
            pipeline.addLast(new KryoEncoder(defaultCodec));
            pipeline.addLast(new KryoDecoder(defaultCodec));
            break;
    }
}
 
Example #9
Source File: MixServerInitializer.java    From incubator-hivemall with Apache License 2.0 6 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()));
    }

    MixMessageEncoder encoder = new MixMessageEncoder();
    MixMessageDecoder decoder = new MixMessageDecoder();

    if (throughputCounter != null) {
        pipeline.addLast(throughputCounter, decoder, encoder, requestHandler);
    } else {
        pipeline.addLast(decoder, encoder, requestHandler);
    }
}
 
Example #10
Source File: RfbClientHandshaker.java    From jfxvnc with Apache License 2.0 6 votes vote down vote up
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {

    channel.writeAndFlush(Unpooled.wrappedBuffer(version.getBytes())).addListener((ChannelFuture future) -> {
      if (!future.isSuccess()) {
        promise.setFailure(future.cause());
        return;
      }

      ChannelPipeline p = future.channel().pipeline();
      ChannelHandlerContext ctx = p.context(ProtocolHandshakeHandler.class);
      p.addBefore(ctx.name(), "rfb-handshake-decoder", newRfbClientDecoder());
      p.addBefore(ctx.name(), "rfb-handshake-encoder", newRfbClientEncoder());
      promise.setSuccess();

    });
    return promise;
  }
 
Example #11
Source File: Receiver.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
Example #12
Source File: ThriftServerInitializer.java    From drift with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel)
{
    ChannelPipeline pipeline = channel.pipeline();

    if (sslContextSupplier.isPresent()) {
        if (allowPlainText) {
            pipeline.addLast(new OptionalSslHandler(sslContextSupplier.get().get()));
        }
        else {
            pipeline.addLast(sslContextSupplier.get().get().newHandler(channel.alloc()));
        }
    }

    pipeline.addLast(new ThriftProtocolDetection(
            new ThriftServerHandler(methodInvoker, requestTimeout, timeoutExecutor),
            maxFrameSize,
            assumeClientsSupportOutOfOrderResponses));
}
 
Example #13
Source File: Bootstrap.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
void init(Channel channel) throws Exception {
    ChannelPipeline p = channel.pipeline();
    p.addLast(config.handler());

    final Map<ChannelOption<?>, Object> options = options0();
    synchronized (options) {
        setChannelOptions(channel, options, logger);
    }

    final Map<AttributeKey<?>, Object> attrs = attrs0();
    synchronized (attrs) {
        for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
            channel.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
        }
    }
}
 
Example #14
Source File: HttpUploadServerInitializer.java    From netty-4.1.22 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 HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());

    // Remove the following line if you don't want automatic content compression.
    pipeline.addLast(new HttpContentCompressor());

    pipeline.addLast(new HttpUploadServerHandler());
}
 
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: HttpUploadServerInitializer.java    From tools-journey 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 HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());

    // Remove the following line if you don't want automatic content compression.
    pipeline.addLast(new HttpContentCompressor());

    pipeline.addLast(new HttpUploadServerHandler());
}
 
Example #17
Source File: HttpFileServerChannelInitializer.java    From tajo with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
  ChannelPipeline pipeline = channel.pipeline();

  // Uncomment the following lines if you want HTTPS
  //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
  //engine.setUseClientMode(false);
  //pipeline.addLast("ssl", new SslHandler(engine));

  pipeline.addLast("encoder", new HttpResponseEncoder());
  pipeline.addLast("decoder", new HttpRequestDecoder());
  pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
  pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

  pipeline.addLast("handler", new HttpFileServerHandler());
}
 
Example #18
Source File: BasicServer.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the {@code SocketChannel}.
 *
 * This method initializes a new channel created by the {@code ServerBootstrap}
 *
 * The default implementation create a remote connection, configures a default pipeline
 * which handles coding/decoding messages, handshaking, timeout and error handling based
 * on {@code RpcConfig} instance provided at construction time.
 *
 * On each call to this method, every handler added must be a new instance. As of now, the
 * handlers cannot be shared across connections.
 *
 * Subclasses can override it to add extra handlers if needed.
 *
 * @param ch the socket channel
 */
protected void initChannel(final SocketChannel ch) throws SSLException {
  C connection = initRemoteConnection(ch);
  connection.setChannelCloseHandler(newCloseListener(ch, connection));

  final ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(PROTOCOL_ENCODER, new RpcEncoder("s-" + rpcConfig.getName()));
  pipeline.addLast(MESSAGE_DECODER, newDecoder(connection.getAllocator()));
  pipeline.addLast(HANDSHAKE_HANDLER, newHandshakeHandler(connection));

  if (rpcConfig.hasTimeout()) {
    pipeline.addLast(TIMEOUT_HANDLER,
        new LoggingReadTimeoutHandler(connection, rpcConfig.getTimeout()));
  }

  pipeline.addLast(MESSAGE_HANDLER, new InboundHandler(connection));
  pipeline.addLast(EXCEPTION_HANDLER, new RpcExceptionHandler<>(connection));
}
 
Example #19
Source File: NettyClientFilter.java    From springBoot-study 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(0, 4, 0, TimeUnit.SECONDS));  
    
    //传输的协议 Protobuf
    ph.addLast(new ProtobufVarint32FrameDecoder());
    ph.addLast(new ProtobufDecoder(UserMsg.getDefaultInstance()));
    ph.addLast(new ProtobufVarint32LengthFieldPrepender());
    ph.addLast(new ProtobufEncoder());
   
    //业务逻辑实现类
    ph.addLast("nettyClientHandler",nettyClientHandler);
  
}
 
Example #20
Source File: NettyClientInit.java    From jus with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();

    // Enable HTTPS if necessary.
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }

    p.addLast(new HttpClientCodec());

    // Remove the following line if you don't want automatic content decompression.
    p.addLast(new HttpContentDecompressor());

    // Uncomment the following line if you don't want to handle HttpContents.
    p.addLast(new HttpObjectAggregator(1048576));

    p.addLast(nettyHttpClientHandler);
}
 
Example #21
Source File: ChanelInitializerHandler.java    From netty-pubsub with MIT License 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
       ChannelPipeline pipeline = ch.pipeline();
       pipeline.addLast(new IdleStateHandler(0,0,35));
       pipeline.addLast(new IdleStateTrigger());
       //��ư��ĸ�ʽ 1�ֽڹ̶���ͷ  1�ֽڹ�����  1�ֽڣ��ж��Ƿ����topic�ֶΣ� 4�ֽڹ̶������ֶ�   12�ֽڹ̶�topic���DZ��룩  ʣ���ֽ�����
       pipeline.addLast(new LengthFieldBasedFrameDecoder(2048, 3, 4, 0, 0));
       pipeline.addLast(new MessageToPoDecoder());
       //�����֤�Ĵ�����
       //pipeline.addLast("auth",new AuthenticationHandler());
       //���Э�鴦����
       pipeline.addLast( "message-process", new MessageProcessHandler());
       pipeline.addLast(new MessageEncoder());
       //pipeline.addLast("auth",new AuthenticationHandler());
       //pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
}
 
Example #22
Source File: EchoClient.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 if (sslCtx != null) {
                     p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                 }
                 //p.addLast(new LoggingHandler(LogLevel.INFO));
                 p.addLast(new EchoClientHandler());
             }
         });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
 
Example #23
Source File: ChannelPipelineInitializer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private void configureHttp2(Channel ch, ChannelPipeline pipeline) {
    // Using Http2FrameCodecBuilder and Http2MultiplexHandler based on 4.1.37 release notes
    // https://netty.io/news/2019/06/28/4-1-37-Final.html
    Http2FrameCodec codec =
        Http2FrameCodecBuilder.forClient()
                              .headerSensitivityDetector((name, value) -> lowerCase(name.toString()).equals("authorization"))
                              .initialSettings(Http2Settings.defaultSettings().initialWindowSize(clientInitialWindowSize))
                              .frameLogger(new Http2FrameLogger(LogLevel.DEBUG))
                              .build();

    // Connection listeners have higher priority than handlers, in the eyes of the Http2FrameCodec. The Http2FrameCodec will
    // close any connections when a GOAWAY is received, but we'd like to send a "GOAWAY happened" exception instead of just
    // closing the connection. Because of this, we use a go-away listener instead of a handler, so that we can send the
    // exception before the Http2FrameCodec closes the connection itself.
    codec.connection().addListener(new Http2GoAwayEventListener(ch));

    pipeline.addLast(codec);
    ch.attr(HTTP2_CONNECTION).set(codec.connection());

    ch.attr(HTTP2_INITIAL_WINDOW_SIZE).set(clientInitialWindowSize);
    pipeline.addLast(new Http2MultiplexHandler(new NoOpChannelInitializer()));
    pipeline.addLast(new Http2SettingsFrameHandler(ch, clientMaxStreams, channelPoolRef));
    if (healthCheckPingPeriod == null) {
        pipeline.addLast(new Http2PingHandler(HTTP2_CONNECTION_PING_TIMEOUT_SECONDS * 1_000));
    } else if (healthCheckPingPeriod.toMillis() > 0) {
        pipeline.addLast(new Http2PingHandler(saturatedCast(healthCheckPingPeriod.toMillis())));
    }
}
 
Example #24
Source File: RpcClientInitializer.java    From springboot-learn with MIT License 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline cp = socketChannel.pipeline();
    cp.addLast(new RpcEncoder(RpcRequest.class));
    cp.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
    cp.addLast(new RpcDecoder(RpcResponse.class));
    cp.addLast(new RpcClientHandler());
}
 
Example #25
Source File: NettyITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws InterruptedException {
  final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
  final EventLoopGroup workerGroup = new NioEventLoopGroup();
  try {
    final ServerBootstrap bootstrap = new ServerBootstrap()
      .option(ChannelOption.SO_BACKLOG, 1024)
      .group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(final SocketChannel socketChannel) {
          final ChannelPipeline pipeline = socketChannel.pipeline();
          pipeline.addLast(new HttpServerCodec());
          pipeline.addLast(new HttpServerHandler());
        }
      });

    bootstrap.bind(8086).sync().channel();
    client();
  }
  finally {
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
  }

  TestUtil.checkSpan(new ComponentSpanCount("netty", 2, true));
}
 
Example #26
Source File: WebSocketServerInitializer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    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 WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true));
    pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH));
    pipeline.addLast(new WebSocketFrameHandler());
}
 
Example #27
Source File: PipeLineBuilder.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void buildCodec(Channel channel, ConnectionImpl connection) {
	ChannelPipeline pipeline = channel.pipeline();
	PacketDecoder decoder = new PacketDecoder(connection);
	PacketEncoder encoder = new PacketEncoder(connection);
	pipeline.addAfter(ChannelHandlers.RAW_CAPTURE_RECEIVE, ChannelHandlers.DECODER_TRANSFORMER, decoder);
	pipeline.addAfter(ChannelHandlers.RAW_CAPTURE_SEND, ChannelHandlers.ENCODER_TRANSFORMER, encoder);
	connection.initCodec(PacketCodec.instance, encoder, decoder);
}
 
Example #28
Source File: SpdyServerInitializer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    p.addLast(sslCtx.newHandler(ch.alloc()));
    // Negotiates with the browser if SPDY or HTTP is going to be used
    p.addLast(new SpdyOrHttpHandler());
}
 
Example #29
Source File: FastdfsPool.java    From fastdfs-client with Apache License 2.0 5 votes vote down vote up
public void channelCreated(Channel channel) throws Exception {
    if (LOG.isInfoEnabled()) {
        LOG.info("channel created : {}", channel.toString());
    }

    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast(new IdleStateHandler(readTimeout, 0, idleTimeout, TimeUnit.MILLISECONDS));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new FastdfsHandler());
}
 
Example #30
Source File: TtyServerInitializer.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpObjectAggregator(64 * 1024));
  pipeline.addLast(new HttpRequestHandler("/ws"));
  pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
  pipeline.addLast(new TtyWebSocketFrameHandler(group, handler));
}