学习netty的小案例,用netty实现一个http服务。
HttpNettyServer
public class HttpNettyServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup(1);
try {
ServerBootstrap sb = new ServerBootstrap();
sb.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new HttpChannelInitializer());
ChannelFuture cf = sb.bind(8888).sync();
cf.addListener(future -> {
if (future.isSuccess()) {
System.out.println("http is ready");
}
});
cf.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
HttpChannelInitializer
public class HttpChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) {
// 向管道加入处理器
// 获取 管道
ChannelPipeline pipeline = ch.pipeline();
// 加入netty 提供的 HttpSeverCodec codec => [coder - decoder]
// HttpSeverCodec 是 netty 提供的 处理Http 的编-解码器
pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
// 增加一个自定义的 handler
pipeline.addLast("MyHttpServerHandler", new HttpServerHandler());
System.out.println("ok~~~~");
}
}
HttpServerHandler
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
// 读取客户端数据
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
System.out.println("1对应的channel=" + ctx.channel() + ",pipeline=" + ctx
.pipeline() + " 通过pipeline获取channel" + ctx.pipeline().channel());
System.out.println("2当前ctx的handler=" + ctx.handler());
System.out.println("3msg类型:" + msg.getClass());
System.out.println("4客户端地址:" + ctx.channel().remoteAddress());
// 回复信息给浏览器[Http 协议]
if (msg instanceof HttpRequest) {
System.out.println("5ctx 类型=" + ctx.getClass());
System.out.println("6pipeline hashcode" + ctx.pipeline().hashCode() + " TestHttpServerHandler hash=" + this.hashCode());
HttpRequest request = (HttpRequest) msg;
// 获取Uri,过滤指定的资源
String uri = request.uri();
System.out.println(uri);
if (uri.contains("favicon.ico")) {
return;
}
ByteBuf content = Unpooled.copiedBuffer("Hello,我是服务器", CharsetUtil.UTF_8);
// 构造一个Http的响应,即httpResponse
FullHttpResponse httpResponse
= new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
// 返回
ctx.writeAndFlush(httpResponse);
}
}
}
地址:http://localhost:8888/
控制台
完!
腾云先锋(TDP,Tencent Cloud Developer Pioneer)是腾讯云GTS官方组建并运营的技术开发者群体。这里有最专业的开发者&客户,能与产品人员亲密接触,专有的问题&需求反馈渠道,有一群志同道合的兄弟姐妹。来加入属于我们开发者的社群吧!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有