Skip to content

测速 ​

1、功能概述 ​

SpeedTestHandler 是基于 Tio-Boot HTTP 框架的一个测速接口,能根据客户端传入的 size 参数(单位 MB)动态生成指定大小的二进制 payload 并返回,用于测试网络带宽及客户端接收性能。


2、Handler 实现示例 ​

说明disableGzip(true):示例中调用关闭框架的 gzip 压缩逻辑,以避免压缩影响带宽测试。 流失输出,防止超出内存大小

java
package nexus.io.kit.handler;

import nexus.io.aio.BytePacket;
import nexus.io.tio.boot.http.TioRequestContext;
import nexus.io.tio.core.Tio;
import nexus.io.tio.http.common.HttpRequest;
import nexus.io.tio.http.common.HttpResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SpeedTestHandler {

  /**
   * 测速接口:GET /speed/test?size={size in MB}
   */
  public HttpResponse output(HttpRequest request) {
    HttpResponse httpResponse = TioRequestContext.getResponse();

    // 读取 size 参数(单位 MB)
    Long sizeMb = request.getLong("size");
    if (sizeMb == null || sizeMb < 0) {
      sizeMb = 500L;
    }

    long totalBytes = sizeMb * 1024L * 1024L;
    httpResponse.setContentType("application/octet-stream");
    httpResponse.setContentLength(totalBytes);
    //告诉编码器,已经设置了响应头的Content-Length,不要再计算
    httpResponse.setSkipAddContentLength(true);
    //发送请求头
    Tio.bSend(request.channelContext, httpResponse);

    long chunkBytes = 1 * 1024L * 1024L;
    // 生成指定大小的零字节数组
    byte[] payload = new byte[(int) chunkBytes];

    // 计算字节数
    for (int i = 1; i < sizeMb + 1; i++) {

      BytePacket bytePacket = new BytePacket(payload);
      // 向客户端发送消息
      log.info("send:{},{}", i, chunkBytes);
      Tio.bSend(request.channelContext, bytePacket);
    }

    //关闭连接
    Tio.close(request.channelContext, "close");

    //告诉编码器 这个httpResponse已经发送过了,不要再次发送
    httpResponse.setSend(false);
    return httpResponse;
  }
}

4、接口说明 ​

属性值
请求方式GET
请求 URLhttp://{host}:{port}/speed/test
查询参数size:要生成的响应大小,单位 MB;缺省或非法时默认为 500
响应内容指定大小的二进制零数据流

4、测试方法 ​

  1. 用 curl 测速并输出总耗时

    bash

curl -o /dev/null -s -w 'total_time: %{time_total}s\n' "http://localhost/speed/test?size=100"


* `-o /dev/null`:丢弃响应体
* `-s`:静默模式,不显示进度
* `-w 'total_time: %{time_total}s\n'`:打印总耗时

2. **使用 shell 的 time 命令**

```bash
time curl -o /dev/null "http://localhost/speed/test?size=100"

这样还能同时看到 real / user / sys 等信息。

  1. 确认无 gzip

    bash
    curl -I "http://localhost/speed/test?size=100"

    应该看到响应头中不含 Content-Encoding: gzip,且 Content-Length 接近 104857600(100×1024²)。


5、常见问题 ​

  • 为什么收到的数据远小于预期? 可能因为框架自动启用了 gzip 压缩。请确认已在代码或全局配置中禁用压缩。
  • 大体量响应会导致 OOM? 推荐使用流式分块写出,而非一次性 new byte[size]。

至此,可根据实际部署环境(host、port、Tio-Boot 版本等)将示例代码和测试命令替换或调整,即可完成大规模带宽测试。祝测试顺利!

MIT Licensed