netty android 服务端,Android使用Netty搭建Web服务器

在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中

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值