我做了一个简单的网络服务器,但每次我在短时间内多次刷新页面时它都会崩溃。我只是在浏览器中输入 127.0.0.1:8080,然后按 F5 发送垃圾邮件。这是重现此问题的代码:
void main()
{
HttpServer server = new HttpServer();
server.addRequestHandler((req) => true, handleGET);
server.listen('127.0.0.1', 8080);
}
void handleGET(HttpRequest req, HttpResponse res)
{
var requestedFile = ".${req.path}";
if(req.path == "/")
{
requestedFile = requestedFile.concat("index.html");
}
File file = new File(requestedFile);
file.exists().then((bool found) {
if(found)
{
file.openInputStream().pipe(res.outputStream);
}
else
{
res.statusCode = HttpStatus.NOT_FOUND;
res.outputStream.close();
}
});
}
我得到的错误如下:
Unhandled exception:
StreamException: Stream closed
#0 _SocketOutputStream._write (dart:io:6017:30)
#1 _HttpResponse._writeHeader (dart:io:5981:18)
#2 _HttpRequestResponseBase._ensureHeadersSent (dart:io:2696:19)
#3 _HttpResponse._streamClose (dart:io:2921:23)
#4 _HttpOutputStream.close (dart:io:3078:36)
#5 _pipe.<anonymous closure> (dart:io:6271:28)
#6 _BaseDataInputStream._checkScheduleCallbacks.issueCloseCallback (dart:io:6231:59)
#7 _Timer._createTimerHandler._handleTimeout (dart:io:6804:28)
#8 _Timer._createTimerHandler._handleTimeout (dart:io:6812:7)
#9 _Timer._createTimerHandler.<anonymous closure> (dart:io:6820:23)
#10 _ReceivePortImpl._handleMessage (dart:isolate-patch:37:92)
通常在此市长例外之前,我会收到一堆警告,例如 WSASend failed: 10053 但这些不会使服务器崩溃。如果此问题与某些特定实现有关,我在 Windows 上工作。