Java Code Examples for io.netty.channel.Channel#pipeline()

The following examples show how to use io.netty.channel.Channel#pipeline() . 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: 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 2
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void buildBungeeClientCodec(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	NetworkDataCache cache = new NetworkDataCache();
	cache.storeIn(connection);
	pipeline.replace(PipelineUtils.PACKET_DECODER, PipelineUtils.PACKET_DECODER, new FromClientPacketDecoder(connection, cache));
	pipeline.replace(PipelineUtils.PACKET_ENCODER, PipelineUtils.PACKET_ENCODER, new ToClientPacketEncoder(connection, cache));
	pipeline.get(CustomHandlerBoss.class).setHandlerChangeListener((handler) -> {
		try {
			return (handler instanceof UpstreamBridge) ? new EntityRewriteUpstreamBridge(
				ReflectionUtils.getFieldValue(handler, "con"), connection.getVersion()
			) : handler;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	});
}
 
Example 3
Source File: AbstractServerChannelManager.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * 设置日志是否开启
 *
 * @param key     客户端关键字,须保证唯一
 * @param enabled 是否开启,true为开启
 */
public void setLoggingEnabled(String key, boolean enabled, Class<?> channelManagerClass, String loggingName) {
    if (!initialized) {
        throw new IllegalArgumentException("服务没有初始化成功");
    }

    ClientEntry entry = clientEntries.get(key);
    if (null == entry) {
        throw new NullPointerException("根据[" + key + "]查找不到对应的ClientEntry对象,可能没有注册成功,请检查!");
    }

    Channel channel = entry.getChannel();
    if (null == channel) {
        LOG.debug("根据[{}]没有找到对应的channel/pipeline,退出处理!", key);
        return;
    }

    ChannelPipeline pipeline = channel.pipeline();
    if (enabled && pipeline.get(loggingName) == null) {
        pipeline.addFirst(loggingName,
                new LoggingHandler(channelManagerClass));
    } else if (!enabled && pipeline.get(loggingName) != null) {
        pipeline.remove(loggingName);
    }
}
 
Example 4
Source File: InitialPacketDecoder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void setProtocol(Channel channel, ProtocolVersion version) {
	ConnectionImpl connection = prepare(channel, version);
	IPipeLineBuilder builder = InitialPacketDecoder.BUILDERS.get(connection.getVersion());
	builder.buildBungeeClientCodec(channel, connection);
	if (encapsulatedinfo == null) {
		builder.buildBungeeClientPipeLine(channel, connection);
	} else {
		ChannelPipeline pipeline = channel.pipeline();
		pipeline.replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new VarIntFrameDecoder());
		if (encapsulatedinfo.hasCompression()) {
			pipeline.addAfter(PipelineUtils.FRAME_DECODER, "decompress", new PacketDecompressor());
			pipeline.addAfter(PipelineUtils.FRAME_PREPENDER, "compress", new PacketCompressor(256));
		}
		if ((encapsulatedinfo.getAddress() != null) && connection.getRawAddress().getAddress().isLoopbackAddress()) {
			connection.changeAddress(encapsulatedinfo.getAddress());
		}
	}
	buffer.readerIndex(0);
	channel.pipeline().firstContext().fireChannelRead(buffer.unwrap());
}
 
Example 5
Source File: RpcServer.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
/**
     * Initialize all processors
     * @return
     */
    @Override
    protected ChannelInitializer<? extends Channel> newWorkerChannelHandler() {
        return new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                RpcServerChannelHandler rpcServerHandler = new RpcServerChannelHandler();
                for (Instance instance : instanceMap.values()) {
                    rpcServerHandler.addInstance(instance.instance,instance.requestMappingName,instance.version,instance.methodToParameterNamesFunction,annotationMethodToMethodNameFunction,true);
                }

                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new RpcDecoder(messageMaxLength));
                pipeline.addLast(new RpcEncoder());
                pipeline.addLast(rpcServerHandler);

                //TrafficShaping
//                pipeline.addLast(new ChannelTrafficShapingHandler());
            }
        };
    }
 
Example 6
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 7
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example 8
Source File: ProtoServerChannelInitializer.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
  ChannelPipeline pipeline = channel.pipeline();
  pipeline.addLast("MonitorServerHandler", new MonitorServerHandler());
  pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
  pipeline.addLast("protobufDecoder", new ProtobufDecoder(defaultInstance));
  pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
  pipeline.addLast("protobufEncoder", new ProtobufEncoder());
  pipeline.addLast("handler", handler);
}
 
Example 9
Source File: NRpcProtocol.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void addPipeline(Channel channel) throws Exception {
    RpcServerChannelHandler rpcServerHandler = new RpcServerChannelHandler();
    rpcServerHandler.getAopList().addAll(rpcServerAopList);
    for (Instance instance : instanceMap.values()) {
        rpcServerHandler.addRpcServerInstance(instance.requestMappingName,instance.version,
                instance.checkGetRpcServerInstance());
    }
    ChannelPipeline pipeline = channel.pipeline();
    pipeline.addLast(new RpcDecoder(messageMaxLength));
    pipeline.addLast(new RpcEncoder());
    pipeline.addLast(rpcServerHandler);
}
 
Example 10
Source File: TcpServerPipelineFactory.java    From gruffalo with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(final Channel channel) throws Exception {
  final ChannelPipeline pipeline = channel.pipeline();
  pipeline.addLast("idleStateHandler", new IdleStateHandler(readerIdleTimeSeconds, 0, 0));
  pipeline.addLast("framer", framerFactory.getLineFramer());
  pipeline.addLast("decoder", decoder);
  pipeline.addLast("batchHandler", metricBatcherFactory.getMetricBatcher());
  pipeline.addLast("publishHandler", publishHandler);
}
 
Example 11
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 12
Source File: SocketExceptionHandlingTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new BuggyChannelHandler());
    pipeline.addLast(exceptionHandler);
}
 
Example 13
Source File: HttpServerPipelineConfigurator.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
    ChannelUtil.disableWriterBufferWatermark(ch);

    final ChannelPipeline p = ch.pipeline();
    p.addLast(new FlushConsolidationHandler());
    p.addLast(ReadSuppressingHandler.INSTANCE);
    configurePipeline(p, port.protocols(), null);
}
 
Example 14
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 15
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 16
Source File: NettyChannelInitializer.java    From ChatServer with Artistic License 2.0 5 votes vote down vote up
/**
 * 채널 파이프라인 설정.
 * Netty.Server.Configuration.NettyServerConfiguration 에서 등록한 Bean 을 이용해 사용자의 통신을 처리할 Handler 도 등록.
 * Netty.Server.Handler.JsonHandler 에서 실제 사용자 요청 처리.
 *
 * @param channel
 * @throws Exception
 */
@Override
protected void initChannel(Channel channel) throws Exception {

	ChannelPipeline channelPipeline = channel.pipeline();

	switch (transferType) {

		case "websocket":

			channelPipeline
					.addLast(new HttpServerCodec())
					.addLast(new HttpObjectAggregator(65536))
					.addLast(new WebSocketServerCompressionHandler())
					.addLast(new WebSocketServerProtocolHandler(transferWebsocketPath, transferWebsocketSubProtocol, transferWebsocketAllowExtensions))
					.addLast(new LoggingHandler(LogLevel.valueOf(logLevelPipeline)))
					.addLast(websocketHandler);

		case "tcp":
		default:

			channelPipeline
					.addLast(new LineBasedFrameDecoder(Integer.MAX_VALUE))
					.addLast(STRING_DECODER)
					.addLast(STRING_ENCODER)
					.addLast(new LoggingHandler(LogLevel.valueOf(logLevelPipeline)))
					.addLast(jsonHandler);

	}

}
 
Example 17
Source File: SslProvider.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
public void addSslHandler(Channel channel, @Nullable SocketAddress remoteAddress, boolean sslDebug) {
	SslHandler sslHandler;

	if (remoteAddress instanceof InetSocketAddress) {
		InetSocketAddress sniInfo = (InetSocketAddress) remoteAddress;
		sslHandler = getSslContext()
				.newHandler(channel.alloc(), sniInfo.getHostString(), sniInfo.getPort());

		if (log.isDebugEnabled()) {
			log.debug(format(channel, "SSL enabled using engine {} and SNI {}"),
					sslHandler.engine().getClass().getSimpleName(), sniInfo);
		}
	}
	else {
		sslHandler = getSslContext().newHandler(channel.alloc());

		if (log.isDebugEnabled()) {
			log.debug(format(channel, "SSL enabled using engine {}"),
					sslHandler.engine().getClass().getSimpleName());
		}
	}

	configure(sslHandler);

	ChannelPipeline pipeline = channel.pipeline();
	if (pipeline.get(NettyPipeline.ProxyHandler) != null) {
		pipeline.addAfter(NettyPipeline.ProxyHandler, NettyPipeline.SslHandler, sslHandler);
	}
	else {
		pipeline.addFirst(NettyPipeline.SslHandler, sslHandler);
	}

	if (pipeline.get(NettyPipeline.LoggingHandler) != null) {
		pipeline.addAfter(NettyPipeline.LoggingHandler, NettyPipeline.SslReader, new SslReadHandler());
		if (sslDebug) {
			pipeline.addBefore(NettyPipeline.SslHandler,
					NettyPipeline.SslLoggingHandler,
					new LoggingHandler("reactor.netty.tcp.ssl"));
		}

	}
	else {
		pipeline.addAfter(NettyPipeline.SslHandler, NettyPipeline.SslReader, new SslReadHandler());
	}
}
 
Example 18
Source File: SocketIOChannelInitializer.java    From socketio with Apache License 2.0 4 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  // Flash policy file
  if (isFlashSupported) {
    pipeline.addLast(FLASH_POLICY_HANDLER, flashPolicyHandler);
  }
  // SSL
  if (sslContext != null) {
    pipeline.addLast(SSL_HANDLER, sslContext.newHandler(ch.alloc()));
  }

  // HTTP
  pipeline.addLast(HTTP_REQUEST_DECODER, new HttpRequestDecoder());
  pipeline.addLast(HTTP_CHUNK_AGGREGATOR, new HttpObjectAggregator(MAX_HTTP_CONTENT_LENGTH));
  pipeline.addLast(HTTP_RESPONSE_ENCODER, new HttpResponseEncoder());
  if (isHttpCompressionEnabled) {
    pipeline.addLast(HTTP_COMPRESSION, new HttpContentCompressor());
  }

  // Flash resources
  if (isFlashSupported) {
    pipeline.addLast(FLASH_RESOURCE_HANDLER, flashResourceHandler);
  }

  // Socket.IO
  pipeline.addLast(SOCKETIO_PACKET_ENCODER, packetEncoderHandler);
  pipeline.addLast(SOCKETIO_HANDSHAKE_HANDLER, handshakeHandler);
  pipeline.addLast(SOCKETIO_DISCONNECT_HANDLER, disconnectHandler);
  if (isWebsocketCompressionEnabled) {
    pipeline.addLast(WEBSOCKET_COMPRESSION, new WebSocketServerCompressionHandler());
  }
  pipeline.addLast(SOCKETIO_WEBSOCKET_HANDLER, webSocketHandler);
  if (isFlashSupported) {
    pipeline.addLast(SOCKETIO_FLASHSOCKET_HANDLER, flashSocketHandler);
  }
  pipeline.addLast(SOCKETIO_XHR_POLLING_HANDLER, xhrPollingHandler);
  if (isJsonpSupported) {
    pipeline.addLast(SOCKETIO_JSONP_POLLING_HANDLER, jsonpPollingHandler);
  }
  pipeline.addLast(SOCKETIO_HEARTBEAT_HANDLER, heartbeatHandler);
  pipeline.addLast(eventExecutorGroup, SOCKETIO_PACKET_DISPATCHER, packetDispatcherHandler);

  if (pipelineModifier != null) {
    pipelineModifier.modifyPipeline(pipeline);
  }
}
 
Example 19
Source File: PipeLineBuilder.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void buildBungeeClientPipeLine(Channel channel, Connection connection) {
	ChannelPipeline pipeline = channel.pipeline();
	pipeline.replace(PipelineUtils.FRAME_DECODER, PipelineUtils.FRAME_DECODER, new NoOpFrameDecoder());
	pipeline.replace(PipelineUtils.FRAME_PREPENDER, PipelineUtils.FRAME_PREPENDER, new NoOpFrameEncoder());
}
 
Example 20
Source File: WebSocketClientHandshaker.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
/**
 * Validates and finishes the opening handshake initiated by {@link #handshake}}.
 *
 * @param channel
 *            Channel
 * @param response
 *            HTTP response containing the closing handshake details
 */
public final void finishHandshake(Channel channel, FullHttpResponse response) {
    verify(response);

    // Verify the subprotocol that we received from the server.
    // This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol
    String receivedProtocol = response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL);
    receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null;
    String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : "";
    boolean protocolValid = false;

    if (expectedProtocol.isEmpty() && receivedProtocol == null) {
        // No subprotocol required and none received
        protocolValid = true;
        setActualSubprotocol(expectedSubprotocol); // null or "" - we echo what the user requested
    } else if (!expectedProtocol.isEmpty() && receivedProtocol != null && !receivedProtocol.isEmpty()) {
        // We require a subprotocol and received one -> verify it
        for (String protocol : StringUtil.split(expectedSubprotocol, ',')) {
            if (protocol.trim().equals(receivedProtocol)) {
                protocolValid = true;
                setActualSubprotocol(receivedProtocol);
                break;
            }
        }
    } // else mixed cases - which are all errors

    if (!protocolValid) {
        throw new WebSocketHandshakeException(String.format(
                "Invalid subprotocol. Actual: %s. Expected one of: %s",
                receivedProtocol, expectedSubprotocol));
    }

    setHandshakeComplete();

    ChannelPipeline p = channel.pipeline();
    // Remove decompressor from pipeline if its in use
    HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
    if (decompressor != null) {
        p.remove(decompressor);
    }

    // Remove aggregator if present before
    HttpObjectAggregator aggregator = p.get(HttpObjectAggregator.class);
    if (aggregator != null) {
        p.remove(aggregator);
    }

    ChannelHandlerContext ctx = p.context(HttpResponseDecoder.class);
    if (ctx == null) {
        ctx = p.context(HttpClientCodec.class);
        if (ctx == null) {
            throw new IllegalStateException("ChannelPipeline does not contain " +
                    "a HttpRequestEncoder or HttpClientCodec");
        }
        p.replace(ctx.name(), "ws-decoder", newWebsocketDecoder());
    } else {
        if (p.get(HttpRequestEncoder.class) != null) {
            p.remove(HttpRequestEncoder.class);
        }
        p.replace(ctx.name(),
                "ws-decoder", newWebsocketDecoder());
    }
}