我似乎有一个命名管道101问题.我有一个非常简单的设置来连接从C++非托管应用程序传输到C#托管应用程序的单工命名管道.管道连接,但我不能通过管道发送"消息",除非我关闭看起来冲洗缓冲区并传递消息的句柄.就像消息被阻止一样.我试过反转客户端/服务器的角色,并使用不同的标志组合调用它们,没有任何运气.我可以轻松地从C#托管到C++非托管的另一个方向发送消息.有没有人有任何见解.你们中的任何人都可以成功地将C++中的消息发送到C#managed吗?我可以找到许多内部管理或非管理管道的例子,但不能管理到非管理的管道 - 只是声称能够做到这一点.
在清单中,为了清楚起见,我省略了很多包装材料.我认为相关的关键位是管道连接/创建/读取和写入方法.这里不要过分担心阻塞/线程.
C#服务器端
// This runs in its own thread and so it is OK to block
private void ConnectToClient()
{
// This server will listen to the sending client
if (m_InPipeStream == null)
{
m_InPipeStream =
new NamedPipeServerStream("TestPipe", PipeDirection.In, 1);
}
// Wait for client to connect to our server
m_InPipeStream.WaitForConnection();
// Verify client is running
if (!m_InPipeStream.IsConnected)
{
return;
}
// Start listening for messages on the client stream
if (m_InPipeStream != null && m_InPipeStream.CanRead)
{ …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用两个简单的 C# 表单解决方案在我的 Win-XP 工作站上实现双向命名管道通信。一种用于客户端,一种用于服务器。它们看起来几乎相同并且使用 NamedPipeServerStream 和 NamedPipeClientStream (.NET 3.5)。客户端和服务器都通过PipeDirection.InOut设置为双向通信
启动事件的顺序是: 1) 启动服务器。它等待来自客户端的连接。2) 启动客户端,它立即找到并连接到服务器。同样,服务器完成与客户端的连接。3) 客户端和服务器都启动他们的“读取”线程,然后创建流读取器的实例。然后这些线程调用 ReadLn() 并阻塞 - 等待数据。在所有情况下,自动刷新都是正确的。
然后我使用 streamwriter.WriteLn() 将字符串数据从服务器发送到客户端(反之亦然)。但是,执行永远不会从该调用返回。我不知道为什么,任何见解都会受到极大的欢迎。
我花了大量时间研究关于这个主题的所有内容,但我仍然遗漏了一些东西。
客户端和服务器代码片段如下所示:
服务器:
private void ListenForClients()
{
// Only one server as this will be a 1-1 connection
m_pipeServerStream = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1);
// Wait for a client to connect
m_pipeServerStream.WaitForConnection();
// Ccould not create handle - server probably not running
if (!m_pipeServerStream.IsConnected)
return;
// Create a stream writer which flushes after every write
m_pipeServerWriter …Run Code Online (Sandbox Code Playgroud)