如何使用f#编写命名管道服务器来为许多客户端服务?

时间:2017-01-06 02:59:52

标签: f#

我已经写了一个f#命名的管道服务器:

let a=new NamedPipeServerStream("a")
a.WaitForConnection()
let reader=new StreamReader(a)

let rec loop()=
    let b=reader.ReadLine()
    match b with 
    |b' when String.IsNullOrEmpty(b')->()
    |_->
        Console.WriteLine b
        loop()

loop()

此服务器可以工作,但仅适用于一个客户端。当客户端退出时,服务器也会退出。

如何编写命名管道服务器,如tcp服务器,可以为许多客户端服务,并且永不停止?

1 个答案:

答案 0 :(得分:1)

根据这里的C#示例MSDN,您需要使用多个线程从NamedPipeServerStream读取服务多个客户端(考虑在循环函数中使用Async方法)。以下示例可同时为最多4个客户端提供服务。

let MaxPipes = 4

let pipe = new NamedPipeServerStream("a", PipeDirection.InOut,MaxPipes)
let rec loop () = async{
  pipe.WaitForConnection()
  let reader = new StreamReader(pipe)
  let b = reader.ReadLine()
  return! loop ()
}

for i in [1..MaxPipes] do
  Async.Start (loop ())