2012-12-12 51 views
4

我製作了一個簡單的Web服務器,但每次我在很短的時間內刷新頁面時就會崩潰。我只需在我的瀏覽器中輸入127.0.0.1:8080,然後用F5發送垃圾郵件。這裏是重現此問題的代碼:使用F5發送垃圾郵件時Web服務器崩潰

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上工作。

回答

2

由於您正在非常快速地重新加載,您的代碼最終會嘗試寫入已關閉的套接字。因此,您應該捕獲StreamException並忽略它。有人可能會認爲,io庫應該會幫助你多一點。我剛剛提出了這個bug:

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

+0

請問,你能告訴我如何捕捉這個異常?我也可以得到一個SocketIOException:寫入失敗(操作系統錯誤:建立的連接被主機中的軟件終止,errno = 10053)即使我的匹配器函數總是返回false server.addRequestHandler((req)=> false,handleGET ); – user1896395

+0

要捕捉異常,請將代碼包裝在try {}塊中 - 請參閱以下要點:https://gist.github.com/4272378 –

+0

@ChrisBuckett,因爲這是異步代碼,所以我真的不認爲使用try塊將會有所幫助。這是因爲執行發生在try塊不再在堆棧上時運行的回調中。由於此錯誤(http://code.google.com/p/dart/issues/detail?id=7356),我很難嘗試此代碼,但是,我認爲正確的做法是添加一個server.onError處理程序。 –

相關問題