Java 类io.netty.handler.codec.http.HttpResponseDecoder 实例源码

项目:mpush    文件:NettyHttpClient.java   
@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}
项目:GameServerFramework    文件:NHttpRequest.java   
@Override
public void configNewChannel(NioSocketChannel channel) {
    super.configNewChannel(channel);
    ChannelPipeline pipeline = channel.pipeline();
    // 添加 SSL 数据支持
    if (requestConfig.https()) {
        SslContext sslContent = NettyCenter.singleInstance().getSimpleClientSslContext();
        SSLEngine engine = sslContent.newEngine(channel.alloc());
        pipeline.addLast("ssl", new SslHandler(engine));
    }
    // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
    pipeline.addLast("decoder", new HttpResponseDecoder());
    // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
    pipeline.addLast("encoder", new HttpRequestEncoder());
    // 接收的请求累计器
    pipeline.addLast("aggegator", new HttpObjectAggregator(0x30000));
    // mime 类型写出
    pipeline.addLast("streamew", new ChunkedWriteHandler());
    // 添加解压器
    pipeline.addLast("decompressor", new HttpContentDecompressor());
    // add new handler
    pipeline.addLast("handler", new NettyHttpRequestChannelHandler());
}
项目:carbon-transports    文件:RedirectChannelInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (sslEngine != null) {
        if (log.isDebugEnabled()) {
            log.debug("adding ssl handler");
        }
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new HttpContentCompressor());
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount
            , chunkDisabled, originalChannelContext, isIdleHandlerOfTargetChannelRemoved);
    ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
}
项目:carbon-transports    文件:HTTPClientRedirectTestCase.java   
/**
 * Check whether, redirect request is written to the backend when a redirect response is received.
 *
 * @throws URISyntaxException
 * @throws IOException
 */
@Test
public void unitTestForRedirectHandler() throws URISyntaxException, IOException {
    EmbeddedChannel embeddedChannel = new EmbeddedChannel();
    embeddedChannel.pipeline().addLast(new HttpResponseDecoder());
    embeddedChannel.pipeline().addLast(new HttpRequestEncoder());
    embeddedChannel.pipeline().addLast(new RedirectHandler(null, false, 5, false));
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT,
            Unpooled.EMPTY_BUFFER);
    response.headers().set(HttpHeaders.Names.LOCATION, FINAL_DESTINATION);
    embeddedChannel.attr(Constants.ORIGINAL_REQUEST)
            .set(createHttpRequest(Constants.HTTP_GET_METHOD, FINAL_DESTINATION));
    embeddedChannel.writeInbound(response);
    embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    assertNotNull(embeddedChannel.readOutbound());
}
项目:carbon-transports    文件:HTTPClientRedirectTestCase.java   
/**
 * When the maximum redirect count reached, channel should not do any more redirects.
 *
 * @throws URISyntaxException
 * @throws IOException
 */
@Test
public void unitTestForRedirectLoop() throws URISyntaxException, IOException {
    EmbeddedChannel embeddedChannel = new EmbeddedChannel();
    embeddedChannel.pipeline().addLast(new HttpResponseDecoder());
    embeddedChannel.pipeline().addLast(new HttpRequestEncoder());
    embeddedChannel.pipeline()
            .addLast(Constants.IDLE_STATE_HANDLER, new IdleStateHandler(50000, 50000, 0, TimeUnit.MILLISECONDS));
    embeddedChannel.pipeline().addLast(new RedirectHandler(null, false, 5, false, null, false));
    HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT,
            Unpooled.EMPTY_BUFFER);
    response.headers().set(HttpHeaders.Names.LOCATION, FINAL_DESTINATION);
    embeddedChannel.attr(Constants.ORIGINAL_REQUEST)
            .set(createHttpRequest(Constants.HTTP_GET_METHOD, FINAL_DESTINATION));
    embeddedChannel.attr(Constants.RESPONSE_FUTURE_OF_ORIGINAL_CHANNEL).set(new HttpResponseFutureImpl());
    TargetChannel targetChannel = new TargetChannel(null, null);
    targetChannel.setChannel(embeddedChannel);
    embeddedChannel.attr(Constants.TARGET_CHANNEL_REFERENCE).set(targetChannel);
    embeddedChannel.attr(Constants.REDIRECT_COUNT).set(5);
    embeddedChannel.writeInbound(response);
    embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
    assertNull(embeddedChannel.readOutbound());
}
项目:urmia    文件:HttpProxyBackendInitializer.java   
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline p = ch.pipeline();


    if(directWriteBack) {
        p.addLast("encoder", new HttpRequestEncoder());
        p.addLast(new DirectWriteBackHttpProxyBackendHandler(inboundCtx.channel()));
    } else {
        p.addLast("encoder", new HttpRequestEncoder());

        p.addLast("decoder", new HttpResponseDecoder());
        //p.addLast("aggregator", new HttpObjectAggregator(2048));
        p.addLast(new HttpProxyBackendHandler(inboundCtx, index));
    }

}
项目:util4j    文件:HttpClientInitHandler.java   
@Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        if(sslCtx!=null)
        {
            p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
        }
        p.addLast(new HttpResponseDecoder());
        //限制contentLength
        p.addLast(new HttpObjectAggregator(65536));
        p.addLast(new HttpRequestEncoder());
        //大文件传输处理
//      p.addLast(new ChunkedWriteHandler());
        p.addLast(new DefaultListenerHandler<HttpResponse>(listener));
    }
项目:study-netty    文件:HttpClient.java   
public void connect(String host, int port) throws Exception {
    EventLoopGroup 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 {
                // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
                ch.pipeline().addLast(new HttpResponseDecoder());
                // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
                ch.pipeline().addLast(new HttpRequestEncoder());
                ch.pipeline().addLast(new HttpClientInboundHandler());
            }
        });

        // Start the client.
        ChannelFuture f = b.connect(host, port).sync();

        URI uri = new URI("http://127.0.0.1:8844");
        String msg = "Are you ok?";
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

        // 构建http请求
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
        // 发送http请求
        f.channel().write(request);
        f.channel().flush();
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
    }

}
项目:netty-tutorials    文件:HttpXmlClient.java   
public void connect(int port) throws Exception {
    // 配置客户端NIO线程组
    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 {
                        ch.pipeline().addLast("http-decoder",
                                new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator",
                                new HttpObjectAggregator(65536));
                        // XML解码器
                        ch.pipeline().addLast(
                                "xml-decoder",
                                new HttpXmlResponseDecoder(Order.class,
                                        true));
                        ch.pipeline().addLast("http-encoder",
                                new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder",
                                new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler",
                                new HttpXmlClientHandler());
                    }
                });

        // 发起异步连接操作
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
项目:zbus    文件:ProxyClient.java   
public ProxyClient(String address, final EventLoop loop) {  
    super(address, loop);     

    codec(new CodecInitializer() {
        @Override
        public void initPipeline(List<ChannelHandler> p) {
            p.add(new HttpRequestEncoder()); 
            p.add(new HttpResponseDecoder());  
            p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
            p.add(new MessageCodec());
        }
    });  

    onDisconnected(new DisconnectedHandler() { 
        @Override
        public void onDisconnected() throws IOException {
            log.info("Disconnected from(%s) ID=%s", serverAddress(), clientId);
            ProxyClient.this.close();
        }
    }); 

    onError(new ErrorHandler() { 
        @Override
        public void onError(Throwable e, Session session) throws IOException {
            ProxyClient.this.close();
        }
    });
}
项目:zbus    文件:MessageClient.java   
protected void initSupport(ServerAddress address, final EventLoop loop){
    if(address.getServer() != null){
        support = new InProcClient<Message, Message>(address.getServer().getIoAdaptor());
        return;
    }

    TcpClient<Message, Message> tcp = new TcpClient<Message, Message>(address, loop);
    support = tcp;

    tcp.codec(new CodecInitializer() {
        @Override
        public void initPipeline(List<ChannelHandler> p) {
            p.add(new HttpRequestEncoder()); 
            p.add(new HttpResponseDecoder());  
            p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
            p.add(new MessageCodec());
        }
    }); 

    tcp.startHeartbeat(heartbeatInterval, new HeartbeatMessageBuilder<Message>() { 
        @Override
        public Message build() { 
            Message hbt = new Message();
            hbt.setCommand(Message.HEARTBEAT);
            return hbt;
        } 
    });  
}
项目:flashback    文件:ChannelMediator.java   
private void initChannelPipeline(ChannelPipeline pipeline, ServerChannelHandler serverChannelHandler,
    int idleTimeoutMsec) {
  pipeline.addLast("decoder", new HttpResponseDecoder());
  pipeline.addLast("encoder", new HttpRequestEncoder());
  pipeline.addLast("idle", new IdleStateHandler(0, 0, idleTimeoutMsec / 1000));
  pipeline.addLast("handler", serverChannelHandler);
}
项目:netty-book    文件:HttpXmlClient.java   
public void connect(int port) throws Exception {
// 配置客户端NIO线程组
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 {
            ch.pipeline().addLast("http-decoder",
                new HttpResponseDecoder());
            ch.pipeline().addLast("http-aggregator",
                new HttpObjectAggregator(65536));
            // XML解码器
            ch.pipeline().addLast(
                "xml-decoder",
                new HttpXmlResponseDecoder(Order.class,
                    true));
            ch.pipeline().addLast("http-encoder",
                new HttpRequestEncoder());
            ch.pipeline().addLast("xml-encoder",
                new HttpXmlRequestEncoder());
            ch.pipeline().addLast("xmlClientHandler",
                new HttpXmlClientHandle());
        }
        });

    // 发起异步连接操作
    ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

    // 当代客户端链路关闭
    f.channel().closeFuture().sync();
} finally {
    // 优雅退出,释放NIO线程组
    group.shutdownGracefully();
}
   }
项目:netty4.0.27Learn    文件:WebSocketClientHandshaker.java   
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
项目:netty4.0.27Learn    文件:WebSocketServerHandshaker08Test.java   
private static void testPerformOpeningHandshake0(boolean subProtocol) {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "8");

    if (subProtocol) {
        new WebSocketServerHandshaker08(
                "ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);
    } else {
        new WebSocketServerHandshaker08(
                "ws://example.com/chat", null, false, Integer.MAX_VALUE).handshake(ch, req);
    }

    ByteBuf resBuf = (ByteBuf) ch.readOutbound();

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(resBuf);
    HttpResponse res = (HttpResponse) ch2.readInbound();

    Assert.assertEquals(
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
    if (subProtocol) {
        Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    } else {
        Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    }
    ReferenceCountUtil.release(res);
}
项目:netty4.0.27Learn    文件:WebSocketServerHandshaker00Test.java   
private static void testPerformOpeningHandshake0(boolean subProtocol) {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(new DefaultFullHttpRequest(
            HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));

    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_KEY1, "4 @1  46546xW%0l 1 5");
    req.headers().set(Names.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1  .P00");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");

    if (subProtocol) {
        new WebSocketServerHandshaker00(
                "ws://example.com/chat", "chat", Integer.MAX_VALUE).handshake(ch, req);
    } else {
        new WebSocketServerHandshaker00(
                "ws://example.com/chat", null, Integer.MAX_VALUE).handshake(ch, req);
    }

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(ch.readOutbound());
    HttpResponse res = (HttpResponse) ch2.readInbound();

    Assert.assertEquals("ws://example.com/chat", res.headers().get(Names.SEC_WEBSOCKET_LOCATION));
    if (subProtocol) {
        Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    } else {
        Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    }
    LastHttpContent content = (LastHttpContent) ch2.readInbound();

    Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
    content.release();
}
项目:netty4.0.27Learn    文件:WebSocketServerHandshaker13Test.java   
private static void testPerformOpeningHandshake0(boolean subProtocol) {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "13");

    if (subProtocol) {
        new WebSocketServerHandshaker13(
                "ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);
    } else {
        new WebSocketServerHandshaker13(
                "ws://example.com/chat", null, false, Integer.MAX_VALUE).handshake(ch, req);
    }

    ByteBuf resBuf = (ByteBuf) ch.readOutbound();

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(resBuf);
    HttpResponse res = (HttpResponse) ch2.readInbound();

    Assert.assertEquals(
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
    if (subProtocol) {
        Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    } else {
        Assert.assertNull(res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    }
    ReferenceCountUtil.release(res);
}
项目:hope-tactical-equipment    文件:HttpXmlClient.java   
public void connect(int port) throws Exception {
    // 配置客户端NIO线程组
    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 {
                        ch.pipeline().addLast("http-decoder",
                                new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator",
                                new HttpObjectAggregator(65536));
                        // XML解码器
                        ch.pipeline().addLast(
                                "xml-decoder",
                                new HttpXmlResponseDecoder(Order.class,
                                        true));
                        ch.pipeline().addLast("http-encoder",
                                new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder",
                                new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler",
                                new HttpXmlClientHandle());
                    }
                });

        // 发起异步连接操作
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 当代客户端链路关闭
        f.channel().closeFuture().sync();
    } finally {
        // 优雅退出,释放NIO线程组
        group.shutdownGracefully();
    }
}
项目:carbon-transports    文件:HTTPClientInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (proxyServerConfiguration != null) {
        if (proxyServerConfiguration.getProxyUsername() != null
                && proxyServerConfiguration.getProxyPassword() != null) {
            ch.pipeline().addLast("proxyServer",
                    new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress(),
                            proxyServerConfiguration.getProxyUsername(),
                            proxyServerConfiguration.getProxyPassword()));
        } else {
            ch.pipeline()
                    .addLast("proxyServer", new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress()));
        }
    }
    if (sslEngine != null) {
        log.debug("adding ssl handler");
        ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
    }
    ch.pipeline().addLast("compressor", new CustomHttpContentCompressor(chunkDisabled));
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler());
    if (httpTraceLogEnabled) {
        ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
                              new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
    }
    if (followRedirect) {
        if (log.isDebugEnabled()) {
            log.debug("Follow Redirect is enabled, so adding the redirect handler to the pipeline.");
        }
        RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount
                , chunkDisabled);
        ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
    }
    handler = new TargetHandler();
    ch.pipeline().addLast(Constants.TARGET_HANDLER, handler);
}
项目:jetstream    文件:HttpClient.java   
private void createChannelPipeline() {

        if (isPipelineCreated())
            return;

        m_workerGroup = new NioEventLoopGroup(getConfig().getNumWorkers(), new NameableThreadFactory("Jetstream-HttpClientWorker"));
        m_bootstrap = new Bootstrap();
        m_bootstrap.group(m_workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,  getConfig()
                .getConnectionTimeoutInSecs())
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("timeout", new IdleStateHandler(0, getConfig().getIdleTimeoutInSecs(), 0));
                        ch.pipeline().addLast("decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                        ch.pipeline().addLast("encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("aggregator", new HttpObjectAggregator(m_config.getMaxContentLength()));
                        ch.pipeline().addLast(m_httpRequestHandler);
                    }
                });

        if (getConfig().getRvcBufSz() > 0) {
            m_bootstrap.option(ChannelOption.SO_RCVBUF, (int) getConfig().getRvcBufSz());
        }

        if ( getConfig().getSendBufSz() > 0) {
            m_bootstrap.option(ChannelOption.SO_SNDBUF, (int) getConfig().getSendBufSz());
        }
        createdPipeline();

    }
项目:javase-study    文件:HttpStaticFileServerInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("encoder", new HttpResponseDecoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("handler", new HttpStaticFileServerHandler());
}
项目:javase-study    文件:HttpDecoderEncoderInitializer.java   
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    if (client) {
        pipeline.addLast("decoder", new HttpResponseDecoder());
        pipeline.addLast("encoder", new HttpRequestEncoder());
    } else {
        pipeline.addLast("decoder", new HttpRequestDecoder());
        pipeline.addLast("encoder", new HttpResponseEncoder());
    }
}
项目:netty4study    文件:WebSocketClientHandshaker.java   
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
项目:netty4study    文件:WebSocketClientHandshaker.java   
/**
 * 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);
    setActualSubprotocol(response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL));
    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);
    }

    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());
    }
}
项目:netty4study    文件:WebSocketServerHandshaker08Test.java   
@Test
public void testPerformOpeningHandshake() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "8");

    new WebSocketServerHandshaker08(
            "ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);

    ByteBuf resBuf = (ByteBuf) ch.readOutbound();

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(resBuf);
    HttpResponse res = (HttpResponse) ch2.readInbound();

    Assert.assertEquals(
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
    Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    ReferenceCountUtil.release(res);
}
项目:netty4study    文件:WebSocketServerHandshaker00Test.java   
@Test
public void testPerformOpeningHandshake() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(new DefaultFullHttpRequest(
            HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));

    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_KEY1, "4 @1  46546xW%0l 1 5");
    req.headers().set(Names.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1  .P00");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");

    new WebSocketServerHandshaker00(
            "ws://example.com/chat", "chat", Integer.MAX_VALUE).handshake(ch, req);

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(ch.readOutbound());
    HttpResponse res = (HttpResponse) ch2.readInbound();

    Assert.assertEquals("ws://example.com/chat", res.headers().get(Names.SEC_WEBSOCKET_LOCATION));
    Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    LastHttpContent content = (LastHttpContent) ch2.readInbound();

    Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
    content.release();
}
项目:netty4study    文件:WebSocketServerHandshaker13Test.java   
@Test
public void testPerformOpeningHandshake() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "13");

    new WebSocketServerHandshaker13(
            "ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);

    ByteBuf resBuf = (ByteBuf) ch.readOutbound();

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(resBuf);
    HttpResponse res = (HttpResponse) ch2.readInbound();

    Assert.assertEquals(
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
    Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    ReferenceCountUtil.release(res);
}
项目:xio    文件:Recipes.java   
public static HttpResponse decodeResponse(List<ByteBuf> payload) {
  EmbeddedChannel channel = new EmbeddedChannel();

  channel
      .pipeline()
      .addLast("http response decoder", new HttpResponseDecoder())
      .addLast("http message aggregator", new HttpObjectAggregator(1048576));

  for (ByteBuf buffer : payload) {
    channel.writeInbound(buffer);
  }

  HttpResponse response = channel.readInbound();
  return response;
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketClientHandshaker.java   
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketClientHandshaker.java   
/**
 * 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);
    setActualSubprotocol(response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_PROTOCOL));
    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);
    }

    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());
    }
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketServerHandshaker08Test.java   
@Test
public void testPerformOpeningHandshake() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toString().toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "8");

    new WebSocketServerHandshaker08(
            "ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);

    ByteBuf resBuf = ch.readOutbound();

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(resBuf);
    HttpResponse res = ch2.readInbound();

    Assert.assertEquals(
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
    Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    ReferenceCountUtil.release(res);
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketServerHandshaker00Test.java   
@Test
public void testPerformOpeningHandshake() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(new DefaultFullHttpRequest(
            HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII)));

    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toString().toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_KEY1, "4 @1  46546xW%0l 1 5");
    req.headers().set(Names.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1  .P00");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");

    new WebSocketServerHandshaker00(
            "ws://example.com/chat", "chat", Integer.MAX_VALUE).handshake(ch, req);

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(ch.readOutbound());
    HttpResponse res = ch2.readInbound();

    Assert.assertEquals("ws://example.com/chat", res.headers().get(Names.SEC_WEBSOCKET_LOCATION));
    Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    LastHttpContent content = ch2.readInbound();

    Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
    content.release();
}
项目:netty-netty-5.0.0.Alpha1    文件:WebSocketServerHandshaker13Test.java   
@Test
public void testPerformOpeningHandshake() {
    EmbeddedChannel ch = new EmbeddedChannel(
            new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());

    FullHttpRequest req = ReferenceCountUtil.releaseLater(
            new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat"));
    req.headers().set(Names.HOST, "server.example.com");
    req.headers().set(Names.UPGRADE, WEBSOCKET.toString().toLowerCase());
    req.headers().set(Names.CONNECTION, "Upgrade");
    req.headers().set(Names.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
    req.headers().set(Names.SEC_WEBSOCKET_ORIGIN, "http://example.com");
    req.headers().set(Names.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
    req.headers().set(Names.SEC_WEBSOCKET_VERSION, "13");

    new WebSocketServerHandshaker13(
            "ws://example.com/chat", "chat", false, Integer.MAX_VALUE).handshake(ch, req);

    ByteBuf resBuf = ch.readOutbound();

    EmbeddedChannel ch2 = new EmbeddedChannel(new HttpResponseDecoder());
    ch2.writeInbound(resBuf);
    HttpResponse res = ch2.readInbound();

    Assert.assertEquals(
            "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", res.headers().get(Names.SEC_WEBSOCKET_ACCEPT));
    Assert.assertEquals("chat", res.headers().get(Names.SEC_WEBSOCKET_PROTOCOL));
    ReferenceCountUtil.release(res);
}
项目:zbus    文件:MqClient.java   
private void buildSupport(ServerAddress serverAddress, final EventLoop loop, long heartbeatInterval){
    this.token = serverAddress.getToken();
    if(serverAddress.server != null){
        support = new InProcClient<Message, Message>(serverAddress.server);
        return;
    } 
    String address = serverAddress.address;
    if(address == null){
        throw new IllegalArgumentException("ServerAddress missing address property");
    }

    if (address.startsWith("ipc://")) {
        throw new IllegalArgumentException("IPC not implemented yet!");
        //TODO IPC client support
    }

    //default to TCP 
    if(address.startsWith("tcp://")){
        serverAddress.address = address.substring("tcp://".length());
    }

    TcpClient<Message, Message> tcp = new TcpClient<Message, Message>(serverAddress, loop);
    support = tcp;
    tcp.codec(new CodecInitializer() {
        @Override
        public void initPipeline(List<ChannelHandler> p) {
            p.add(new HttpRequestEncoder()); 
            p.add(new HttpResponseDecoder());  
            p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
            p.add(new io.zbus.transport.http.MessageCodec());
            p.add(new io.zbus.mq.MessageCodec());
        }
    }); 

    tcp.startHeartbeat(heartbeatInterval, new HeartbeatMessageBuilder<Message>() { 
        @Override
        public Message build() { 
            Message hbt = new Message();
            hbt.setCommand(Message.HEARTBEAT);
            return hbt;
        }
    });  
}
项目:netty4.0.27Learn    文件:WebSocketClientHandshaker.java   
/**
 * 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());
    }
}