下面列出了怎么用 io.netty.handler.codec.http.HttpResponseEncoder 的API类实例代码及写法,或者点击链接到github查看源代码。
@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));
}
@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 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 {
/*
* 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());
}
private ServerBootstrap serverBootstrap() {
boot.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast("decoder", new HttpRequestDecoder())
.addLast("http-aggregator", new HttpObjectAggregator(65536))
// .addLast("encoder", new HttpResponseDecoder())
.addLast("base-encoder", new HttpResponseEncoder())
.addLast("chunk", new ChunkedWriteHandler())
.addLast("handler", new TestHttpServerHandler());
}
}
);
return boot;
}
@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");
}
});
}
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
// Create a default pipeline implementation.
CorsConfig corsConfig = CorsConfig.withAnyOrigin().build();
ChannelPipeline pipeline = ch.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("encoder", new HttpResponseEncoder());
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpObjectAggregator(8388608)); // 8MB
//pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("cors", new CorsHandler(corsConfig));
pipeline.addLast("handler", new HttpStaticFileServerHandler());
}
/**
* 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());
}
@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));
}
}
@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)//自定义处理器
);
}
});
}
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
return new ChannelInboundHandlerAdapter() {
private HttpResponseEncoder encoder = new HttpResponseEncoder();
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
LOG.trace("Received non-SSL request, returning redirect");
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
response.headers().set(HttpHeaderNames.LOCATION, redirectAddress);
LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
encoder.write(ctx, response, ctx.voidPromise());
ctx.flush();
}
};
}
@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);
}
@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());
}
@Test
public void prematureCancel() {
FluxIdentityProcessor<Void> signal = Processors.more().multicastNoBackpressure();
disposableServer =
TcpServer.create()
.host("localhost")
.port(0)
.handle((in, out) -> {
signal.onComplete();
return out.withConnection(c -> c.addHandlerFirst(new HttpResponseEncoder()))
.sendObject(Mono.delay(Duration.ofSeconds(2))
.map(t -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.PROCESSING)))
.neverComplete();
})
.wiretap(true)
.bindNow(Duration.ofSeconds(30));
StepVerifier.create(
createHttpClientForContextWithAddress()
.get()
.uri("/")
.responseContent()
.timeout(signal))
.verifyError(TimeoutException.class);
}
@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));
}
@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 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
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("httpEncoder", new HttpResponseEncoder());
pipeline.addLast("httpDecoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("httpHandler",new HttpHandler());
}
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.option(ChannelOption.SO_BACKLOG, 1024)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
ch.pipeline().addLast("http-aggregator",new HttpObjectAggregator(65535));//�������Ϣת����һ��
ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());//���������������
ch.pipeline().addLast("http-server",new HttpHandler());
}
});
try {
ChannelFuture future = bootstrap.bind(8888).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
@Override
protected ChannelHandler newChannelInitializer() {
return new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ChannelPipeline cp = ch.pipeline();
cp.addLast("decoder", new HttpRequestDecoder());
cp.addLast("encoder", new HttpResponseEncoder());
cp.addLast("aggregator", new HttpObjectAggregator(1048576));
cp.addLast("handler", new ExampleApiHandler());
}
};
}
@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));
}
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 EmbeddedChannel createChannel(ChannelHandler handler) {
return new EmbeddedChannel(
new WebSocketServerProtocolHandler("/test", null, false),
new HttpRequestDecoder(),
new HttpResponseEncoder(),
new MockOutboundHandler(),
handler);
}
private static void testPerformOpeningHandshake0(boolean subProtocol) {
EmbeddedChannel ch = new EmbeddedChannel(
new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());
FullHttpRequest req = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat");
req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "8");
if (subProtocol) {
new WebSocketServerHandshaker08(
"ws://example.com/chat", "chat", false, Integer.MAX_VALUE, false).handshake(ch, req);
} else {
new WebSocketServerHandshaker08(
"ws://example.com/chat", null, false, Integer.MAX_VALUE, false).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(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT));
if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else {
Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
}
ReferenceCountUtil.release(res);
req.release();
}
private static void testPerformOpeningHandshake0(boolean subProtocol) {
EmbeddedChannel ch = new EmbeddedChannel(
new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());
FullHttpRequest req = new DefaultFullHttpRequest(
HTTP_1_1, HttpMethod.GET, "/chat", Unpooled.copiedBuffer("^n:ds[4U", CharsetUtil.US_ASCII));
req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(HttpHeaderNames.ORIGIN, "http://example.com");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY1, "4 @1 46546xW%0l 1 5");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY2, "12998 5 Y3 1 .P00");
req.headers().set(HttpHeaderNames.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 = ch2.readInbound();
Assert.assertEquals("ws://example.com/chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_LOCATION));
if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else {
Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
}
LastHttpContent content = ch2.readInbound();
Assert.assertEquals("8jKS'y:G*Co,Wxa-", content.content().toString(CharsetUtil.US_ASCII));
content.release();
req.release();
}
private static void testPerformOpeningHandshake0(boolean subProtocol) {
EmbeddedChannel ch = new EmbeddedChannel(
new HttpObjectAggregator(42), new HttpRequestDecoder(), new HttpResponseEncoder());
FullHttpRequest req = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, "/chat");
req.headers().set(HttpHeaderNames.HOST, "server.example.com");
req.headers().set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET);
req.headers().set(HttpHeaderNames.CONNECTION, "Upgrade");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_KEY, "dGhlIHNhbXBsZSBub25jZQ==");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, "http://example.com");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "chat, superchat");
req.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, "13");
if (subProtocol) {
new WebSocketServerHandshaker13(
"ws://example.com/chat", "chat", false, Integer.MAX_VALUE, false).handshake(ch, req);
} else {
new WebSocketServerHandshaker13(
"ws://example.com/chat", null, false, Integer.MAX_VALUE, false).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(HttpHeaderNames.SEC_WEBSOCKET_ACCEPT));
if (subProtocol) {
Assert.assertEquals("chat", res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
} else {
Assert.assertNull(res.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL));
}
ReferenceCountUtil.release(res);
req.release();
}