我一直在修改一些示例代码以用于 Web 服务器,这样我就可以在服务器和客户端上运行 dart。但是,我决定要检查 Web 服务器的性能,除了崩溃之外,我印象最深。我在 Ubuntu 上使用“围攻”软件包,使用少数 URL 为网站生成大量流量。
我已经看到它每秒发送 1000 个事务,这对我来说是非常可接受的,但是在运行两到三分钟后,它要么崩溃要么挂起(如果我增加 new_gen_heap_size)。
#import('dart:io');
class FCServer {
String basePath;
void send404(HttpResponse response)
{
response.statusCode = HttpStatus.NOT_FOUND;
response.outputStream.close();
}
void handleRequest(HttpRequest request, HttpResponse response)
{
final String path = request.path == '/' ? '/index.html' : request.path;
final File file = new File('${basePath}${path}');
file.exists().then((bool found) {
if (found)
{
file.fullPath().then((String fullPath) {
if (!fullPath.startsWith(basePath))
{
send404(response);
}
else
{
//print("delivering $fullPath");
response.headers.add("Cache-Control", "max-age=3600");
//file.openInputStream().pipe(response.outputStream);
var file = new File("$fullPath");
//response.headers.set(HttpHeaders.CONTENT_TYPE, "$contentType; charset=UTF-8");
response.outputStream.write(file.readAsBytesSync());
response.outputStream.close();
}
});
}
else
{
send404(response);
}
});
}
void startServer(String basePath)
{
this.basePath = basePath;
var server = new HttpServer();
print("Starting server with basePath: $basePath");
server.listen('192.168.0.14', 8080);
server.listen('127.0.0.1', 8080);
server.defaultRequestHandler = handleRequest;
}
}
FCServer webServe;
main()
{
// Compute base path for the request based on the location of the
// script and then start the server.
webServe = new FCServer();
File script = new File(new Options().script);
script.directory().then((Directory d) {
webServe.startServer(d.path);
});
}
Dart 退出前打印的错误如下:
Exhausted heap space, trying to allocate 128096 bytes.
Exhausted heap space, trying to allocate 112 bytes.
Exception 'Instance of 'OutOfMemoryException'' thrown:
Exiting the process
这是否意味着某处存在内存泄漏?或者有人可以解释发生了什么吗?
编辑:当 new_gen_heap_size 增加到 1024 时,它会在一段时间后挂起,并且无论请求是否传入,单个线程都处于 100%。此时,在运行上述堆大小后,RAM 高达 1.5GB,所以我假设垃圾收集器已经踢了桶,可以这么说。
编辑 2:我修改了代码,以便在初始化时创建一个由 4 个字节组成的列表,然后每次发出请求时,它只是将该列表写入响应并关闭响应。内存使用量仍在快速增长,这表明 Dart 内部存在更深层次的问题。这让我厌倦了将 Dart 用于完整的项目。