Java-->使用netty搭建Http服务器

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 欢迎您的加入.

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值