在Android中使用netty可以很容易搭建一个web服务器;同时具有netty的优良特性:高性能,高可靠性,API易上手等;本篇文章主要介绍在Android中使用netty搭建web服务器的简单过程,对于一些复杂使用,复杂特性不做深究;不甚了解netty的可以先阅读此篇入门文章:Netty在Android中使用
1.服务器配置及启动
在后台线程中执行此方法:
private void startServer() {
try {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(io.netty.channel.socket.SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// http服务器端对request解码
pipeline.addLast(new HttpRequestDecoder());
// http服务器端对response编码
pipeline.addLast(new HttpResponseEncoder());
// 在处理POST消息体时需要加上
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
// 处理发起的请求
pipeline.addLast(new HttpServerHandler());
//在HttpResponseEncoder序列化之前会对response对象进行HttpContentCompressor压缩
pipeline.addLast("compressor", new HttpContentCompressor());
}
});
b.bind(new InetSocketAddress(PORT)).sync();
Log.d(TAG, "HTTP服务启动成功 PORT=" + PORT);
} catch (Exception e) {
e.printStackTrace();
}
}
使用Http进行编解码主要添加:
// http服务器端对request解码
pipeline.addLast(new HttpRequestDecoder());
// http服务器端对response编码
pipeline.addLast(new HttpResponseEncoder());
对发起的请求进行处理:(详细见#2中