Forked from jbrisbin/NettyHttpServerSocketOptions.java
Created
January 3, 2014 03:24
-
-
Save gembin/8232117 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NettyHttpServerSocketOptions extends NettyServerSocketOptions { | |
@Override | |
public final Consumer<ChannelPipeline> pipelineConfigurer() { | |
return new Consumer<ChannelPipeline>() { | |
@Override | |
public void accept(ChannelPipeline pipeline) { | |
pipeline.addLast(new HttpRequestDecoder()); | |
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE)); | |
pipeline.addLast(new HttpResponseEncoder()); | |
} | |
}; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TcpServer<HttpRequest, HttpResponse> server = new TcpServerSpec<HttpRequest, HttpResponse>(NettyTcpServer.class) | |
.env(env) | |
.listen(port) | |
.options(new NettyHttpServerSocketOptions()) | |
.consume(new Consumer<TcpConnection<HttpRequest, HttpResponse>>() { | |
@Override | |
public void accept(final TcpConnection<HttpRequest, HttpResponse> conn) { | |
// Use the Stream API rather than consuming messages directly | |
conn.in() | |
.map(new Function<HttpRequest, HttpResponse>() { | |
@Override | |
public HttpResponse apply(HttpRequest req) { | |
ByteBuf buf = Unpooled.copiedBuffer("Hello World!".getBytes()); | |
int len = buf.readableBytes(); | |
DefaultFullHttpResponse resp = new DefaultFullHttpResponse( | |
HttpVersion.HTTP_1_1, | |
HttpResponseStatus.OK, | |
buf | |
); | |
HttpHeaders hdrs = resp.headers(); | |
hdrs.set(HttpHeaders.Names.CONTENT_LENGTH, len); | |
hdrs.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); | |
hdrs.set(HttpHeaders.Names.CONNECTION, "Keep-Alive"); | |
// NOTE: This would be a fully-formed, "proper" HTTP 1.1 response | |
// if we added Date and Server headers. | |
// If we're just writing the response, then we can return it from a Function. | |
// We only need to send responses later if we're doing long work of some kind | |
// like submitting a batch job to a worker queue. | |
return resp; | |
} | |
}) | |
// the output of a connection is also a Consumer | |
.consume(conn.out()); | |
} | |
}) | |
.get(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment