2010-04-23 52 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() 

也请注意自动冲洗是如何设置调用构造函数和内如何管道运算符用于回声写到管道,造成什么样子(在我看来)像更清晰的代码。

相关问题