netty 起 Http server
2019-08-22 本文已影响0人
lesliefang
public class HttpServer {
private final static Logger logger = LoggerFactory.getLogger(HttpServer.class);
private final int port = 5515;
private final EventLoopGroup bossGroup = new NioEventLoopGroup();
private final EventLoopGroup workerGroup = new NioEventLoopGroup();
public void start() {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 512)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HttpServerCodec());
ch.pipeline().addLast(new HttpObjectAggregator(512 * 1024));
ch.pipeline().addLast(new HttpRequestHandler());
}
});
try {
ChannelFuture bindFuture = bootstrap.bind(port).sync();
bindFuture.channel().closeFuture().addListener(future -> {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
});
logger.info("{} is started on port {}.", this.getClass().getSimpleName(), port);
} catch (Exception e) {
logger.error("{} starts failed!", this.getClass().getSimpleName(), e);
}
}
public void stop() {
logger.info("{} stopped.", this.getClass().getSimpleName());
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
String uri = req.uri(); // 路径
String msg = "<html><body>hello world</body></html>";
FullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
// response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
}