2010-04-23 54 views
3

我是F#的新手。我正嘗試使用命名管道與F#中的java進行通信。下面的代碼工作,但我不知道是否有更好的方法來做到這一點(我知道無限循環是一個壞主意,但這只是一個概念證明),如果任何人有任何想法來改善此代碼,請張貼您的意見。有沒有更好的方式在F#中編寫命名管道?

在此先感謝 Sudaly

open System.IO 
open System.IO.Pipes 
exception OuterError of string 


let continueLooping = true 
while continueLooping do 
    let pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4) 
    printfn "[F#] NamedPipeServerStream thread created." 

    //wait for connection 
    printfn "[F#] Wait for a client to connect" 
    pipeServer.WaitForConnection() 

    printfn "[F#] Client connected." 
    try 
     // Stream for the request. 
     let sr = new StreamReader(pipeServer) 
     // Stream for the response. 
     let sw = new StreamWriter(pipeServer) 
     sw.AutoFlush <- true; 

     // Read request from the stream. 
     let echo = sr.ReadLine(); 

     printfn "[F#] Request message: %s" echo 

     // Write response to the stream. 
     sw.WriteLine("[F#]: " + echo) 

     pipeServer.Disconnect() 

    with 
    | OuterError(str) -> printfn "[F#]ERROR: %s" str 

    printfn "[F#] Client Closing." 
    pipeServer.Close() 

回答

2

那麼,它看起來並不像什麼是投擲OuterError,所以我會刪除該異常類型和未使用的處理。

我不確定你的經驗水平或你正在尋找什麼類型的「更好」。您可以通過閱讀F# async on the server來了解有關異步和避免阻塞線程的更多信息。

2

下面你可以找到對你的代碼的一些修改。你的問題很模糊,所以我不能確切地知道你希望改進代碼的位置,但我的建議使用遞歸而不是while循環(不要擔心堆棧溢出,F#可以很好地處理遞歸,而且整個遞歸位將在編譯時優化爲一個循環),使用使用關鍵字(如C#的使用),並將吞下與客戶端通信過程中發生的任何異常。如果發生異常,服務器將不會偵聽其他連接。

open System.IO 
open System.IO.Pipes 

let main() = 
    printfn "[F#] NamedPipeServerStream thread created." 
    let pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4) 
    let rec loop() = 
     //wait for connection 
     printfn "[F#] Wait for a client to connect" 
     pipeServer.WaitForConnection() 

     printfn "[F#] Client connected." 
     try 
      // Stream for the request. 
      use sr = new StreamReader(pipeServer) 
      // Stream for the response. 
      use sw = new StreamWriter(pipeServer, AutoFlush = true) 

      // Read request from the stream. 
      let echo = sr.ReadLine(); 

      printfn "[F#] Request message: %s" echo 

      // Write response to the stream. 
      echo |> sprintf "[F#]: %s" |> sw.WriteLine 

      pipeServer.Disconnect() 
      if [A CONDITION WHICH TELLS YOU THAT YOU WANT ANOTHER CONNECTION FROM THE CLIENT] then loop() 
     with 
     | _ as e -> printfn "[F#]ERROR: %s" e.Message 
    loop() 
    printfn "[F#] Client Closing." 
    pipeServer.Close() 

也請注意自動沖洗是如何設置調用構造函數和內如何管道運算符用於回聲寫到管道,造成什麼樣子(在我看來)像更清晰的代碼。

相關問題