开发者

Exception thrown by BeginWaitForConnection when reusing a NamedPipeServerStream in .NET 4 after client disconnects

I'm trying to use NamedPipeServerStream to create a named pipe server in .Net 4. I'm using BeginWaitForConnection to wait for the connection, so that I can abort the wait if the server is to be shut down.

Everything works well for the first client --- the connection is ackno开发者_JS百科wledged, the data received, and the response sent OK. However, after the client disconnects everything breaks. I'm calling BeginWaitForConnection again to wait for a new connection, but this is throwing an IOException saying that the "pipe is broken".

How can I wait for a second client on the same pipe?


Create a new instance of NamedPipeServerStream specifying the same pipe, and call BeginWaitForConnection on that.

i.e. Don't try to reuse a NamedPipeServerStream object for different clients: one instance should service one client connection/conversation, then be disposed.

See also Multithreaded NamePipeServer in C#


Another method when using a single client/server configuration is to Disconnect the pipe stream when the client disconnects to clean up the pipe. This allows reuse of the pipe. When you call BeginWaitForConnection again, it will begin accepting connections.

while (true) 
{
    pipe.BeginWaitForConnection();
    // read and write to pipe
    // catch exception when client disconnects
    pipe.Disconnect();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜