类 io.netty.handler.codec.http.HttpRequestDecoder 源码实例Demo

下面列出了怎么用 io.netty.handler.codec.http.HttpRequestDecoder 的API类实例代码及写法,或者点击链接到github查看源代码。


private void switchToHttp(ChannelHandlerContext ctx) {
   ChannelPipeline p = ctx.pipeline();
   p.addLast("http-decoder", new HttpRequestDecoder());
   p.addLast("http-aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
   p.addLast("http-encoder", new HttpResponseEncoder());
   //create it lazily if and when we need it
   if (httpKeepAliveRunnable == null) {
      long httpServerScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_SERVER_SCAN_PERIOD_PROP_NAME, TransportConstants.DEFAULT_HTTP_SERVER_SCAN_PERIOD, nettyAcceptor.getConfiguration());
      httpKeepAliveRunnable = new HttpKeepAliveRunnable();
      Future<?> future = scheduledThreadPool.scheduleAtFixedRate(httpKeepAliveRunnable, httpServerScanPeriod, httpServerScanPeriod, TimeUnit.MILLISECONDS);
      httpKeepAliveRunnable.setFuture(future);
   }
   long httpResponseTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_RESPONSE_TIME_PROP_NAME, TransportConstants.DEFAULT_HTTP_RESPONSE_TIME, nettyAcceptor.getConfiguration());
   HttpAcceptorHandler httpHandler = new HttpAcceptorHandler(httpKeepAliveRunnable, httpResponseTime, ctx.channel());
   ctx.pipeline().addLast("http-handler", httpHandler);
   p.addLast(new ProtocolDecoder(false, true));
   p.remove(this);
}
 

@Override
protected void initChannel(SocketChannel ch) throws Exception {
	
	ChannelPipeline pipeline = ch.pipeline();
	
	if (serverTlsContext != null && serverTlsContext.useTls()) {
		SSLEngine engine = serverTlsContext.getContext().createSSLEngine();
		engine.setUseClientMode(false);
		pipeline.addLast("tls", new SslHandler(engine));
	}
	
	pipeline.addLast("encoder", new HttpResponseEncoder());
       pipeline.addLast("decoder", new HttpRequestDecoder());
       pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
       pipeline.addLast("handler", new Ipcd10WebSocketServerHandler(false));
}
 
源代码3 项目: arcusplatform   文件: IrisUpnpServer.java

private void handleRequest(@Nullable ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
   EmbeddedChannel http = new EmbeddedChannel(new HttpRequestDecoder());

   try {
      http.writeInbound(Unpooled.unreleasableBuffer(packet.content()));
      http.finish();

      while (true) {
         Object result = http.readInbound();
         if (result == null) {
            break;
         }

         if (result instanceof HttpRequest) {
            HttpRequest req = (HttpRequest)result;
            switch (req.getMethod().name()) {
            case "NOTIFY": handleUpnpNotify(packet, req); break;
            case "M-SEARCH": handleUpnpMsearch(packet, req); break;
            default: log.debug("unknown upnp message: {}", req.getMethod()); break;
            }
         } 
      }
   } finally {
      http.finishAndReleaseAll();
   }
}
 

@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());
}
 

private static void testDecodeWholeRequestInMultipleSteps(byte[] content, int fragmentSize) {
    final EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestDecoder());

    final int headerLength = content.length - CONTENT_LENGTH;

    // split up the header
    for (int a = 0; a < headerLength;) {
        int amount = fragmentSize;
        if (a + amount > headerLength) {
            amount = headerLength -  a;
        }

        // if header is done it should produce a HttpRequest
        channel.writeInbound(Unpooled.wrappedBuffer(content, a, amount));
        a += amount;
    }

    for (int i = CONTENT_LENGTH; i > 0; i --) {
        // Should produce HttpContent
        channel.writeInbound(Unpooled.wrappedBuffer(content, content.length - i, 1));
    }
}
 

@Test
public void testHandleTextFrame() {
    CustomTextFrameHandler customTextFrameHandler = new CustomTextFrameHandler();
    EmbeddedChannel ch = createChannel(customTextFrameHandler);
    writeUpgradeRequest(ch);

    if (ch.pipeline().context(HttpRequestDecoder.class) != null) {
        // Removing the HttpRequestDecoder because we are writing a TextWebSocketFrame and thus
        // decoding is not necessary.
        ch.pipeline().remove(HttpRequestDecoder.class);
    }

    ch.writeInbound(new TextWebSocketFrame("payload"));

    assertEquals("processed: payload", customTextFrameHandler.getContent());
}
 

private static void testDecodeWholeRequestInMultipleSteps(byte[] content, int fragmentSize) {
    final EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestDecoder());

    final int headerLength = content.length - CONTENT_LENGTH;

    // split up the header
    for (int a = 0; a < headerLength;) {
        int amount = fragmentSize;
        if (a + amount > headerLength) {
            amount = headerLength -  a;
        }

        // if header is done it should produce a HttpRequest
        channel.writeInbound(Unpooled.wrappedBuffer(content, a, amount));
        a += amount;
    }

    for (int i = CONTENT_LENGTH; i > 0; i --) {
        // Should produce HttpContent
        channel.writeInbound(Unpooled.wrappedBuffer(content, content.length - i, 1));
    }
}
 

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    /*
     * ChannelInboundHandler按照注册的先后顺序执行,ChannelOutboundHandler按照注册的先后顺序逆序执行。
     * HttpRequestDecoder、HttpObjectAggregator、HttpHandler为InboundHandler
     * HttpContentCompressor、HttpResponseEncoder为OutboundHandler
     * 在使用Handler的过程中,需要注意:
     * 1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。
     * 2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。
     * 3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。
     * 4、Handler的消费处理放在最后一个处理。
     */
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    // 启用gzip(由于使用本地存储文件,不能启用gzip)
    //pipeline.addLast(new HttpContentCompressor(1));
    pipeline.addLast(new ChunkedWriteHandler());
    // 将HttpRequestHandler放在业务线程池中执行,避免阻塞worker线程。
    pipeline.addLast(eventExecutorGroup, "httpRequestHandler", new HttpRequestHandler());
}
 
源代码9 项目: pampas   文件: GatewayServer.java

@Override
public ChannelInitializer<SocketChannel> newChannelInitializer() {

    return new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline()
                    .addLast(loggingHandler)
                    .addLast(new IdleStateHandler(30, 0, 10))
                    .addLast("decoder", new HttpRequestDecoder())
                    .addLast("http-aggregator", new HttpObjectAggregator(65536))
                    .addLast("encoder", new HttpResponseEncoder())
                    .addLast("chunk", new ChunkedWriteHandler())
                    .addLast(businessExecutors, "business-handler", new HttpServerHandler())
                    .addLast(new HeartbeatHandler())
                    .addLast(exceptionHandler);

        }
    };
}
 
源代码10 项目: api-gateway-core   文件: FrontFilter.java

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    config.getChannelInboundHandlerList().forEach(pipeline::addLast);
    config.getChannelOutboundHandlerList().forEach(pipeline::addLast);
    pipeline.addLast(new HttpResponseEncoder());
    config.getHttpResponseHandlerList().forEach(pipeline::addLast);
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new HttpObjectAggregator(10 * 1024 * 1024));
    pipeline.addLast(new FrontHandler());
    pipeline.addLast(new ExceptionHandler());


    ch.closeFuture().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            logger.debug("channel close");
        }
    });
}
 

/**
 * Initialize the channel.
 *
 * @param channel the channel.
 */
@Override
public void initChannel(SocketChannel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    if (ssl) {
        try {
            SSLContext sslContext = SSLContext.getDefault();
            SSLEngine sslEngine = sslContext.createSSLEngine();
            sslEngine.setUseClientMode(false);
            pipeline.addLast(new SslHandler(sslEngine));
        } catch (NoSuchAlgorithmException e) {
            if (LOGGER.isLoggable(SEVERE)) {
                LOGGER.log(WARNING, "Unable to match SSL algorithm", e);
            }
        }
    }
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpObjectAggregator(10*1024*1024));
    pipeline.addLast(new NettyHttpServerHandler(httpServerProcessor));
}
 

@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());
}
 
源代码13 项目: util4j   文件: HttpServerInitHandler.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 HttpResponseEncoder());//必须放在最前面,如果decoder途中需要回复消息,则decoder前面需要encoder
		p.addLast(new HttpRequestDecoder());
		p.addLast(new HttpObjectAggregator(65536));//限制contentLength
		//大文件传输处理
//		p.addLast(new ChunkedWriteHandler());
//		p.addLast(new HttpContentCompressor());
		//跨域配置
		CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
		p.addLast(new CorsHandler(corsConfig));
		if(unPoolMsg)
		{
			p.addLast(new DefaultListenerHandler<HttpRequest>(new HttpListenerProxy(listener)));
		}else
		{
			p.addLast(new DefaultListenerHandler<HttpRequest>(listener));
		}
	}
 
源代码14 项目: DistributedID   文件: HttpServer.java

@Override
public void init() {
    super.init();
    b.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(defLoopGroup,
                            new HttpRequestDecoder(),       //请求解码器
                            new HttpObjectAggregator(65536),//将多个消息转换成单一的消息对象
                            new HttpResponseEncoder(),      // 响应编码器
                            new HttpServerHandler(snowFlake)//自定义处理器
                    );
                }
            });

}
 
源代码15 项目: nettythrift   文件: HttpCodecDispatcher.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	if (msg instanceof ByteBuf && ctx.channel().isActive()) {
		boolean isHttpRequest = false;
		ByteBuf buffer = (ByteBuf) msg;
		final int len = 11;
		if (buffer.readableBytes() > len) {
			byte[] dst = new byte[len];
			buffer.getBytes(buffer.readerIndex(), dst, 0, len);
			int n = HttpMethodUtil.method(dst);
			isHttpRequest = n > 2;
		}
		if (isHttpRequest) {
			ChannelPipeline cp = ctx.pipeline();
			String currentName = ctx.name();
			cp.addAfter(currentName, "HttpRequestDecoder", new HttpRequestDecoder());
			cp.addAfter("HttpRequestDecoder", "HttpResponseEncoder", new HttpResponseEncoder());
			cp.addAfter("HttpResponseEncoder", "HttpObjectAggregator", new HttpObjectAggregator(512 * 1024));
			ChannelHandler handler = serverDef.httpHandlerFactory.create(serverDef);
			cp.addAfter("HttpObjectAggregator", "HttpThriftBufDecoder", handler);

			cp.remove(currentName);
		}
	}
	ctx.fireChannelRead(msg);
}
 
源代码16 项目: timely   文件: TestServer.java

@Override
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config.getHttp(), sslCtx));
            ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
            ch.pipeline().addLast("decoder", new HttpRequestDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
            ch.pipeline().addLast("queryDecoder",
                    new timely.netty.http.HttpRequestDecoder(config.getSecurity(), config.getHttp()));
            ch.pipeline().addLast("capture", httpRequests);
        }
    };
}
 
源代码17 项目: SI   文件: HttpServerInitializer.java

@Override
public void initChannel(SocketChannel ch) {
	ChannelPipeline pipeline = ch.pipeline();
	if (sslCtx != null) {
		pipeline.addLast(sslCtx.newHandler(ch.alloc()));
	}
	pipeline.addLast(new HttpResponseEncoder());
	pipeline.addLast(new HttpRequestDecoder());
	// Uncomment the following line if you don't want to handle HttpChunks.
	//pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
	//p.addLast(new HttpObjectAggregator(1048576));
	// Remove the following line if you don't want automatic content compression.
	//pipeline.addLast(new HttpContentCompressor());
	
	// Uncomment the following line if you don't want to handle HttpContents.
	pipeline.addLast(new HttpObjectAggregator(65536));
	pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(READ_TIMEOUT));
	pipeline.addLast("myHandler", new MyHandler());
	
	pipeline.addLast("handler", new HttpServerHandler(listener));
}
 
源代码18 项目: flashback   文件: ProxyInitializer.java

@Override
public void initChannel(SocketChannel socketChannel) {
  ChannelPipeline channelPipeline = socketChannel.pipeline();
  channelPipeline.addLast("decoder", new HttpRequestDecoder());
  channelPipeline.addLast("encoder", new HttpResponseEncoder());
  channelPipeline.addLast("idle", new IdleStateHandler(0, 0, _proxyServer.getClientConnectionIdleTimeout()));
  ChannelMediator channelMediator = new ChannelMediator(socketChannel,
      _proxyServer.getProxyModeControllerFactory(),
      _proxyServer.getDownstreamWorkerGroup(),
      _proxyServer.getServerConnectionIdleTimeout(),
      _proxyServer.getAllChannels());
  ClientChannelHandler clientChannelHandler =
      new ClientChannelHandler(channelMediator, _proxyServer.getConnectionFlowRegistry());

  channelPipeline.addLast("handler", clientChannelHandler);
}
 

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }

    p.addLast(new HttpRequestDecoder());
    // Uncomment the following line if you don't want to handle HttpChunks.
    p.addLast(new HttpObjectAggregator(65536));
    p.addLast(new HttpResponseEncoder());
    // Remove the following line if you don't want automatic content
    // compression.
    p.addLast(new HttpContentCompressor());
    p.addLast(new ApiRequestParser());
}
 

@Override
public void initChannel(SocketChannel channel) throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = channel.pipeline();

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

    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("handler", new ServletNettyHandler(this.dispatcherServlet));
}
 

@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());
}
 

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast(new HttpRequestDecoder());
    // Uncomment the following line if you don't want to handle HttpChunks.
    //p.addLast(new HttpObjectAggregator(1048576));
    p.addLast(new HttpResponseEncoder());
    // Remove the following line if you don't want automatic content compression.
    //p.addLast(new HttpContentCompressor());
    p.addLast(new HttpSnoopServerHandler());
}
 
源代码23 项目: HAP-Java   文件: ServerInitializer.java

@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new LoggingHandler());
  pipeline.addLast(HTTP_HANDLER_NAME, new HttpResponseEncoderAggregate());
  pipeline.addLast(new HttpRequestDecoder());
  pipeline.addLast(new HttpObjectAggregator(MAX_POST));
  pipeline.addLast(blockingExecutorGroup, new AccessoryHandler(homekit));
  allChannels.add(ch);
}
 

@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline p = socketChannel.pipeline();

    p.addLast(new HttpRequestDecoder());
    p.addLast(new HttpObjectAggregator(1024 * 1024));
    p.addLast(new HttpResponseEncoder());

    p.addLast(new HttpServerHandler());
}
 

@Test
public void testInitChannel() throws Exception {
    // Mock Objects
    HttpServerInitializer httpServerInitializer = mock(HttpServerInitializer.class);
    SocketChannel socketChannel = mock(SocketChannel.class);
    ChannelPipeline channelPipeline = mock(ChannelPipeline.class);

    // Mock SocketChannel#pipeline() method
    when(socketChannel.pipeline()).thenReturn(channelPipeline);

    // HttpServerInitializer#initChannel(SocketChannel) call real method
    doCallRealMethod().when(httpServerInitializer).initChannel(socketChannel);

    // Start test for HttpServerInitializer#initChannel(SocketChannel)
    httpServerInitializer.initChannel(socketChannel);

    // Verify 4 times calling ChannelPipeline#addLast() method
    verify(channelPipeline, times(4)).addLast(any(ChannelHandler.class));

    // Verify the order of calling ChannelPipeline#addLast() method
    InOrder inOrder = inOrder(channelPipeline);
    inOrder.verify(channelPipeline).addLast(any(HttpRequestDecoder.class));
    inOrder.verify(channelPipeline).addLast(any(HttpObjectAggregator.class));
    inOrder.verify(channelPipeline).addLast(any(HttpResponseEncoder.class));

    inOrder.verify(channelPipeline).addLast(any(HttpServerHandler.class));
}
 
源代码26 项目: cassandana   文件: NewNettyAcceptor.java

private void initializeWSSTransport(NewNettyMQTTHandler handler, Config conf, SslContext sslContext) {
    LOG.debug("Configuring secure websocket MQTT transport");
    if(!conf.wssEnabled) {
    	return;
    }
    
    int sslPort = conf.wssPort;
    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();
    String host = conf.wssHost;
    final boolean needsClientAuth = conf.certClientAuth;
    initFactory(host, sslPort, "Secure websocket", new PipelineInitializer() {

        @Override
        void init(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast("ssl", createSslHandler(channel, sslContext, needsClientAuth));
            pipeline.addLast("httpEncoder", new HttpResponseEncoder());
            pipeline.addLast("httpDecoder", new HttpRequestDecoder());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());

            configureMQTTPipeline(pipeline, timeoutHandler, handler);
        }
    });
}
 

private void switchToHttp(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("encoder", new HttpResponseEncoder());
    p.addLast("deflater", new HttpContentCompressor());
    p.addLast("handler", new HttpSnoopServerHandler());
    p.remove(this);
}
 

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast(new HttpRequestDecoder());
    // Uncomment the following line if you don't want to handle HttpChunks.
    //p.addLast(new HttpObjectAggregator(1048576));
    p.addLast(new HttpResponseEncoder());
    // Remove the following line if you don't want automatic content compression.
    //p.addLast(new HttpContentCompressor());
    p.addLast(new HttpSnoopServerHandler());
}
 

@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 

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);
}
 
 类方法
 同包方法