Netty下载地址: http://netty.io/downloads.html
我将Netty配置在Android手机上, 发现手机会很卡,但是在PC上,无压力;
下一篇文章, 会介绍在Android手机上搭建Http服务器,(更简单);
开始本文:
1:新建一个Java工程
publicstatic void main(String[] args) throws Exception {
// 配置服务
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HttpSnoopServerInitializer(null));
Channel ch = b.bind(8080).sync().channel();
System.err.println("Open your web browser and navigate to " +
"http" + "://127.0.0.1:" + 8080+ '/');
ch.closeFuture().sync();//启动之后,就可以在浏览器访问了.
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
2:创建HttpSnoopServerInitializer类
public class HttpSnoopServerInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
public HttpSnoopServerInitializer(SslContext sslCtx) {
this.sslCtx = sslCtx;
}
@Override
public void initChannel(SocketChannel ch) {//用来注册需要处理的请求
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
//p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpResponseEncoder());
// Remove the following line if you don't want automatic content compression.
//p.addLast(new HttpContentCompressor());
p.addLast(new HttpSnoopServerHandler());
}
}
3:创建HttpSnoopServerHandler类
“`
public class HttpSnoopServerHandler extends SimpleChannelInboundHandler {
private HttpRequest request;
/** Buffer that stores the response content */
private final StringBuilder buf = new StringBuilder();
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {//收到Http请求之后, 处理就行了
StringBuilder result = new StringBuilder("参数:\n");
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(
request.getUri());
result.append("请求函数:" + queryStringDecoder.path() + "\n");
Map<String, List<String>> params = queryStringDecoder.parameters();
if (!params.isEmpty()) {
for (java.util.Map.Entry<String, List<String>> p : params
.entrySet()) {
String key = p.getKey();
List<String> vals = p.getValue();
for (String val : vals) {
buf.append("PARAM: ").append(key).append(" = ")
.append(val).append("\r\n");
}
result.append("\n" + key + ":" + vals.get(0));
}
buf.append("\r\n");
result.append("\n");
}
DefaultFullHttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(result.toString(), CharsetUtil.UTF_8));
ctx.write(response);//将结果,返回到客户端
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(
ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
基本上,简单通信就完成了;
源代码下载: http://download.csdn.net/detail/angcyo/8787717
至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的加入.