如何使用Java套接字检查网络速度测量与QOS一起正常工作

时间:2019-04-30 08:35:45

标签: java sockets networking qos

我要制作服务器-客户端网络速度测量工具。所以我制作了服务器端程序(打开套接字并发送数据)和客户端程序(连接服务器并接收数据)。

简而言之,客户端将服务器发送的数据存储一段时间(3〜5秒),然后计算接收到的数据除以时间。

我进行了一些测试,然后在本地主机(几乎1GB / s)与另一台机器之间(几乎100MB / s)进行了测试,因为我的路由器不支持GIGA Network。但是当我将网络速度限制为降低0.1Kbps,使用QOS(路由器提供)将速度降低至0.1Kbps时,网络速度仍然接近100MB / s。

// client
private static long cost = 0;
  private static double total = 0;
  private static long start = System.currentTimeMillis();
  public static void main(String[] args) throws Exception {
    Socket socket = new Socket("192.168.0.10", 50000);
    // Socket socket = new Socket("localhost", 50000);
    InputStream input = socket.getInputStream();
    new Thread(() -> {
      long interval = 3_000l;
      try {
        TimeUnit.MILLISECONDS.sleep(interval);
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }
      while (true) {
        cost = System.currentTimeMillis() - start;
        String _total = String.format("%,.2f", total / 1000f / 1000f);
        String _speed = String.format("%,.3f", total / cost / 1000f);
        String _cost = String.format("%,.3f", cost / 1000f);
        System.out.println(new Date() + " -- Read: " + _total + " Mbytes" +
                                                                ", cost: " + _cost + " s" +
                                                                ", speed: " + _speed + " MB/s");
        total = 0;
        start = System.currentTimeMillis();
        try { 
          TimeUnit.MILLISECONDS.sleep(interval);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }).start();
    byte[] bytes = new byte[32 * 1024000]; // 32_000K
    while (true) {
      int read = input.read(bytes);
      if (read < 0)
        break;
      total += read;
    }
//server
  private static ServerSocket server;
  private static OutputStream output;
  private static Socket socket;

  public static void main(String[] args) throws InterruptedException, IOException {
    while (true) {
      try {
        startServer();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        server.close();
        output.close();
        socket.close();
        System.out.println("try to restart server after 2sec");
        TimeUnit.MILLISECONDS.sleep(2000);
        continue;
      }
    }
  }

  public static void startServer() throws IOException {
    server = new ServerSocket(50000);
    System.out.println("start start...");
    socket = server.accept();
    output = socket.getOutputStream();

    byte[] bytes = new byte[32 * 1024000]; // 32000K
    for (int i=0; i<bytes.length; i++) {
      bytes[i] = 127;
    }
    while (true) {
        output.write(bytes);
    }
  }

请告诉我我错过了什么。谢谢。

0 个答案:

没有答案