Is there a better way to write named-pipes in F #?

I am new to F #. I am trying to communicate with java from F # using named pipe. The code below works, but I'm not sure if there is a better way to do this (I know that an infinite loop is a bad idea, but this is just a proof of concept), if someone has an idea to improve this code, write your comments.

Thanks in advance 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()
+3
source share
2 answers

Well, it seems like something is throwing OuterError, so I will remove this type of exception and unused handling.

, "" . F # async , async .

+2

. , , , while ( , F # , ), use (, #) , . , .

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

+2

Source: https://habr.com/ru/post/1742489/


All Articles