Skip to content

Commit dad3019

Browse files
committed
Handle keep alive in echo server
1 parent 19dd2a6 commit dad3019

3 files changed

Lines changed: 13 additions & 15 deletions

File tree

reactivesocket-netty/src/examples/java/io/reactivesocket/netty/EchoServer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ protected void initChannel(Channel ch) throws Exception {
2828
}
2929
});
3030

31-
Channel localhost = b.bind("localhost", 8025).sync().channel();
31+
Channel localhost = b.bind("0.0.0.0", 8025).sync().channel();
3232
localhost.closeFuture().sync();
3333
} finally {
3434
bossGroup.shutdownGracefully();

reactivesocket-netty/src/examples/java/io/reactivesocket/netty/EchoServerHandler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ private static boolean isHttp(int magic1, int magic2) {
5454
private void switchToHttp(ChannelHandlerContext ctx) {
5555
ChannelPipeline p = ctx.pipeline();
5656
p.addLast(new HttpServerCodec());
57-
p.addLast(new HttpObjectAggregator(64 * 1024));
57+
p.addLast(new HttpObjectAggregator(256 * 1024));
5858
p.addLast(httpHandler);
5959
p.remove(this);
6060
}
Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,22 @@
11
package io.reactivesocket.netty;
22

3+
import io.netty.channel.ChannelFutureListener;
34
import io.netty.channel.ChannelHandler;
45
import io.netty.channel.ChannelHandlerContext;
56
import io.netty.channel.SimpleChannelInboundHandler;
6-
import io.netty.handler.codec.http.DefaultFullHttpResponse;
7-
import io.netty.handler.codec.http.FullHttpRequest;
8-
9-
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
10-
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
7+
import io.netty.handler.codec.http.*;
118

129
@ChannelHandler.Sharable
1310
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
1411
@Override
15-
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
16-
ctx.flush();
17-
ctx.close();
18-
}
19-
20-
@Override
21-
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
22-
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, OK, msg.content().copy()));
12+
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
13+
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, request.content().retain());
14+
HttpUtil.setContentLength(response, response.content().readableBytes());
15+
if (HttpUtil.isKeepAlive(request)) {
16+
response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
17+
ctx.writeAndFlush(response);
18+
} else {
19+
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
20+
}
2321
}
2422
}

0 commit comments

Comments
 (0)