Netty充当Http服务器简单示例
2017-06-14 本文已影响50人
蟋蟀哥
Netty的应用场景
- RPC 通信框架
- 长连接服务器
- Http服务器
充当Http服务器实例: 用户向服务器发送请求, 服务器返回给用户Hello World, 先介绍几个基础的概念:
- Channel (通道, 相当于一个连接)
- ChannelHandler (通道处理器, 相当于拦截器, 过滤器)
- Pipeline(管道, 一个Pipeline由多个ChannelHandler构成)
创建项目就不在此多啰嗦, 我使用的是idea, 创建了一个基于gradle的项目, 当然也可以使用maven或者直接去官网下载下jar文件进行导入.
Maven
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.12.Final</version>
</dependency>
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<SocketChannel> {
@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<HttpObject> {
// 此方法用于读取客户端的请求并进行响应
@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 进行查看。