2010-04-23 3 views
3

나는 F #을 처음 사용합니다. 나는 명명 된 파이프를 사용하여 F #에서 java와 통신하려고합니다. 아래의 코드는 작동하지만 더 좋은 방법이 있는지는 잘 모르겠습니다. (무한 루프는 나쁜 생각이지만 개념의 증거 일뿐입니다.) 누군가이 코드를 개선하기위한 아이디어가 있다면 의견을 게시하십시오. . 사전 SudalyF #에서 명명 된 파이프를 작성하는 더 좋은 방법이 있습니까?

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() 


는 또한의 autoflush이 생성자를 호출하고 내에서 설정하는 방법을주의하시기 바랍니다 파이프 라인 연산자 청소기 코드처럼 (내 생각에) 모습의 결과로, 파이프에 에코를 작성하는 데 사용되는 방법.