yanzhenjie / AndServer

:cherries: Web server and web framework of Android platform.
https://yanzhenjie.com/AndServer
Apache License 2.0
3.74k stars 755 forks source link

调整 Socket 发送和接收缓冲区,来优化网络传输性能 #545

Open lsk-boy-f opened 5 months ago

lsk-boy-f commented 5 months ago

背景

Hi,我在使用这个库的时候,发现IO性能比较弱,在局域网中下载速度只有 1-2 MB/s。然后就发现通信 Socket 的发送和接收缓冲区设置都是0

https://github.com/yanzhenjie/AndServer/blob/23a7c15512f5a70a9ce517710a5d04c06a4d57c9/api/src/main/java/com/yanzhenjie/andserver/server/BasicServer.java#L91

是在这个commit 7a7f11f 中为修复性能问题引入的。

缓冲区大小和带宽对应关系

经过测试,缓冲区大小设置到 4MB,局域网速度可以提升到 7.00 MB/s。缓冲区大小和性能的测试结果如下:

缓冲区大小 带宽 (MB/s)
128KB 4.11
512KB 6.51
1MB 6.79
4MB 7.00
8MB 6.74
10MB 4.04

测试代码

BasicServer

 public abstract class BasicServer<T extends BasicServer.Builder> implements Server {
-
-//    static final int BUFFER = 8 * 1024;
+    private static final int BUFFER = (int) (1024 * 1024 * 0.1);

     protected final InetAddress mInetAddress;
     protected final int mPort;
@@ -88,9 +87,9 @@ public abstract class BasicServer<T extends BasicServer.Builder> implements Serv
                                 .setSoReuseAddress(true)
                                 .setTcpNoDelay(true)
                                 .setSoTimeout(mTimeout)
-//                                .setBacklogSize(BUFFER)
-//                                .setRcvBufSize(BUFFER)
-//                                .setSndBufSize(BUFFER)
+                                .setBacklogSize(BUFFER)
+                                .setRcvBufSize(BUFFER)
+                                .setSndBufSize(BUFFER)
                                 .setSoLinger(0)
                                 .build()

TestController

@@ -180,4 +181,11 @@ class TestController {
     List<UserInfo> jsonBody(@RequestBody List<UserInfo> infoList) {
         return infoList;
     }
+
+    @GetMapping("/download")
+    public FileBody download(HttpRequest request, HttpResponse response) {
+
+        return new FileBody(new File("/sdcard/Atlas.mp4"));
+    }
+
 }

测试设备

=== CPU Information ===
Model: Qualcomm Technologies, Inc MSM8998
Cores: 8
=== Memory Information ===
Total Memory: 5214MB
=== Disk Information ===
Total Size: 54G
Used Size: 4.6G
Available Size: 49G

期望结果

调整 Socket 的缓冲区大小,使网络性能提升一下