dart – 使用F5发送垃圾邮件时Web服务器崩溃

我制作了一个简单的Web服务器,但每次我在很短的时间内刷新页面时都会崩溃.我只需在浏览器中输入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失败:10053,但那些不会使服务器崩溃.如果此问题与某些特定实现有关,我在Windows上工作.

最佳答案 因为您很快就会重新加载,所以您的代码最终会尝试写入已经关闭的套接字.因此,您应该捕获StreamException并忽略它.可以说io库应该可以帮到你更多.我刚刚提交了这个错误:

http://code.google.com/p/dart/issues/detail?id=7334&thanks=7334&ts=1355280746

点赞