netty http文件服务器,Netty充当Http服务器简单示例

Netty的应用场景

RPC 通信框架

长连接服务器

Http服务器

充当Http服务器实例: 用户向服务器发送请求, 服务器返回给用户Hello World, 先介绍几个基础的概念:

Channel (通道, 相当于一个连接)

ChannelHandler (通道处理器, 相当于拦截器, 过滤器)

Pipeline(管道, 一个Pipeline由多个ChannelHandler构成)

创建项目就不在此多啰嗦, 我使用的是idea, 创建了一个基于gradle的项目, 当然也可以使用maven或者直接去官网下载下jar文件进行导入.

Maven

io.netty

netty-all

4.1.12.Final

Gradle:

compile 'io.netty:netty-all:4.1.12.Final'

使用的是官网上最新版: 4.1.12.Final

服务器代码实现:

/**

* 服务端

*/

public class TestServer {

public static void main(String[] args) throws Exception {

//定义两个事件循环组, bossGroup用于接收连接, 不对连接进行处理, 转给workerGroup进行处理

EventLoopGroup bossGroup = new NioEventLoopGroup();

EventLoopGroup workerGroup = new NioEventLoopGroup();

try {

ServerBootstrap serverBootstrap = new ServerBootstrap(); //ServerBootstrap用于启动服务端

serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)

.childHandler(new TestServerInitializer()); //TestServerInitializer是我们自己编写的请求初始化器

ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); //绑定端口8899

channelFuture.channel().closeFuture().sync(); //关闭监听

} finally {

//终止事件循环

bossGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

}

/**

* 初始化器

*/

public class TestServerInitializer extends ChannelInitializer {

@Override

protected void initChannel(SocketChannel ch) throws Exception {

ChannelPipeline pipeline = ch.pipeline();

pipeline.addLast("httpServerCodec", new HttpServerCodec());

pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler()); //TestHttpServerHandler自定义的处理器

}

}

/**

* 处理器

*/

public class TestHttpServerHandler extends SimpleChannelInboundHandler {

// 此方法用于读取客户端的请求并进行响应

@Override

protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

if (msg instanceof HttpRequest) {

ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8); //响应内容

FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,

HttpResponseStatus.OK, content); //netty提供的响应对象, 设置http版本, 状态以及响应内容

//设置响应头信息

response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");

response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

ctx.writeAndFlush(response); //返回给客户端

}

}

}

运行项目

使用curl命令:

curl 'http://localhost:8899'

回车便会看到响应内容"Hello World", 也可以直接在浏览器中输入 http://localhost:8899 进行查看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值