2017-01-06 34 views
2

我已经写了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() 

此服务器可以工作,但只有一个client.When客户端退出,服务器戒也。

我该如何编写一个命名管道服务器,如tcp服务器,它可以服务于许多客户端,并且永不停止?

回答

1

根据这里的C#示例MSDN您需要使用多线程来读取NamedPipeServerStream以服务多个客户端(考虑在循环函数中使用异步方法)。以下示例可以同时为多达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())  
+0

Thanks.But当我启动程序时,它很快就退出了。是不是有什么问题? –

+0

为了防止您的控制台应用程序退出,您需要在最后阻止Console.ReadLine()。 – Kevin

相关问题