一些东西。
1-您是否使用相同的管道名称
C++:“\\.\pipe\HyperPipe”
C#:“超级管道”
2-我认为在 C# 方面,使用 ReadToEnd() 可能更好,我只在 C++ 中使用过命名管道,但我认为 ReadToEnd() 会读取消息,因为您正在使用消息
为基础的管道。
3-在C++方面,您尝试使用非阻塞管道并轮询管道以获取连接和数据等。我建议三件事之一。
a - Use a blocking pipe on a separate thread or
b - Use non blocking pipes using Overlapped IO
c - Use non blocking pipes using IOCompletion ports
第一个选项是最简单的,对于听起来你正在做的事情来说,它会很好地扩展。这是一个简单示例的链接 (a)http://msdn.microsoft.com/en-us/library/aa365588(VS.85).aspx http://msdn.microsoft.com/en-us/library/aa365588(VS.85).aspx
4- 确保双方的编码匹配。例如,如果您的 C++ 代码是针对 Unicode 编译的,则必须使用 Unicode 编码读取 C# 端的 Pipe 流。
像下面这样的一些事情。
using (StreamReader rdr = new StreamReader(pipe, System.Text.Encoding.Unicode))
{
System.Console.WriteLine(rdr.ReadToEnd());
}
Update:由于我没有在 C# 中使用过这个,所以我想我应该编写一个小测试。只是使用阻塞管道,没有线程或任何东西,只是为了确认基础工作,这里是非常粗略的测试代码。
C++服务器
#include <tchar.h>
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hPipe = ::CreateNamedPipe(_T("\\\\.\\pipe\\HyperPipe"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
PIPE_UNLIMITED_INSTANCES,
4096,
4096,
0,
NULL);
ConnectNamedPipe(hPipe, NULL);
LPTSTR data = _T("Hello");
DWORD bytesWritten = 0;
WriteFile(hPipe, data, _tcslen(data) * sizeof(TCHAR), &bytesWritten, NULL);
CloseHandle(hPipe);
return 0;
}
C# 客户端
using System;
using System.Text;
using System.IO;
using System.IO.Pipes;
namespace CSPipe
{
class Program
{
static void Main(string[] args)
{
NamedPipeClientStream pipe = new NamedPipeClientStream(".", "HyperPipe", PipeDirection.InOut);
pipe.Connect();
using (StreamReader rdr = new StreamReader(pipe, Encoding.Unicode))
{
System.Console.WriteLine(rdr.ReadToEnd());
}
Console.ReadKey();
}
}
}