【发布时间】:2012-07-11 14:46:33
【问题描述】:
我试图找到任何好的且清晰的异步 NamedPipeServerStream 示例,但找不到适合我的示例。
我想要一个 NamedPipe 服务器,它异步地接受来自客户端的消息。客户很简单,对我来说很好。但是我找不到服务器的例子,或者无法理解它是如何工作的。
现在据我了解,我需要创建 NamedPipeServerStream 对象。让我们这样做:
namedPipeServerStream = new NamedPipeServerStream(PIPENAME, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, BUFFERSIZE, BUFFERSIZE);
似乎有效。 但我不知道,我是否必须使用 PipeSecurity 或 PipeAccessRule?是吗? 我的服务器将作为本地系统中的 Windows 服务运行。
接下来呢?我想我需要使用 BeginWaitForConnection 进行异步连接。让我们看看:
namedPipeServerStream.BeginWaitForConnection(WaitForConnectionAsyncCallback, <some strange thing>);
问题 1:这是什么“奇怪的东西”?怎么用?
问题 2:我应该这样做
while(true)
{
namedPipeServerStream.BeginWaitForConnection(WaitForConnectionAsyncCallback, <some strange thing>);
}
让我的服务器总是等待连接?还是我需要以其他方式进行?
然后……我们来看看 WaitForConnectionAsyncCallback 函数:
private void WaitForConnectionAsyncCallback(IAsyncResult result)
{
Console.WriteLine("Client connected.");
byte[] buff = new byte[BUFFERSIZE];
namedPipeServerStream.Read(buff, 0, namedPipeServerStream.InBufferSize);
string recStr = General.Iso88591Encoding.GetString(buff, 0, namedPipeServerStream.InBufferSize);
Console.WriteLine(" " + recStr);
namedPipeServerStream.EndWaitForConnection(result);
}
..这当然行不通。因为 我不知道如何从流中接收字符串。如何? 现在它引发了一个 InvalidOperationException:
管道尚未连接。
那么如何使用 NamedPipeServerStream 组织异步工作呢?
【问题讨论】:
标签: c# asynchronous named-pipes