命名管道 C# 客户端无法连接到 C++ 服务器

Named Pipe C# client can't connect to C++ server

我正在尝试让 C++ 应用程序让 C# 应用程序知道特定操作何时发生。我尝试这样做的方式是通过命名管道。

我已经在 C++ 应用程序上设置了一个命名管道服务器,它似乎可以正常工作(命名管道已创建 - 它出现在 PipeList 检索到的列表中)和一个命名管道客户端C# 应用程序失败:C# 客户端代码的第一行给出 "Pipe handle has not been set. Did your PipeStream implementation call InitializeHandle?" 错误,第 2 行抛出 "Access to the path is denied" 异常。

我哪里错了?

C++ 服务器代码

CString namedPipeName = "\\.\pipe\TitleChangePipe";

HANDLE pipe = CreateNamedPipe(namedPipeName, PIPE_ACCESS_INBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
if (pipe == INVALID_HANDLE_VALUE) {
    MessageBox(NULL, "Pipe Could Not be Established.", "Error: TCM", MB_ICONERROR);
    return -1;
}

char line[512]; DWORD numRead;

while (true)//just keep doing this
{
    numRead = 1;
    while ((numRead < 10 || numRead > 511) && numRead > 0)
    {
        if (!ReadFile(pipe, line, 512, &numRead, NULL) || numRead < 1) {//Blocking call
            CloseHandle(pipe);                                          //If something went wrong, reset pipe
            pipe = CreateNamedPipe(namedPipeName, PIPE_ACCESS_INBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
            ConnectNamedPipe(pipe, NULL);
            if (pipe == INVALID_HANDLE_VALUE) {
                MessageBox(NULL, "Pipe Could Not be Established.", "Error: TCM", MB_ICONERROR);
                return -1; }
            numRead = 1;
        }
    }
    line[numRead] = '[=10=]';   //Terminate String
}   

CloseHandle(pipe);

C# 客户端代码

var client = new NamedPipeClientStream(".", "TitleChangePipe", PipeDirection.InOut);
client.Connect();
var reader = new StreamReader(client);
var writer = new StreamWriter(client);

while (true)
{
    var input = Console.ReadLine();
    if (String.IsNullOrEmpty(input))
         break;
    writer.WriteLine(input);
    writer.Flush();
    Console.WriteLine(reader.ReadLine());
}

命名管道创建没有正确的参数。

首先你想在管道上读写,所以使用的标志是:PIPE_ACCESS_DUPLEX

那么,这里是同步发送消息。使用这些标志:PIPE_WAIT | PIPE_TYPE_MESSAGE

最后,您只允许在机器上使用此管道的一个实例。显然您至少需要 2 个:一个用于服务器,一个用于客户端。我只想使用无限标志:PIPE_UNLIMITED_INSTANCES

HANDLE pipe = CreateNamedPipe(namedPipeName, PIPE_ACCESS_DUPLEX, \
                              PIPE_WAIT | PIPE_TYPE_MESSAGE, PIPE_UNLIMITED_INSTANCES, \
                              1024, 1024, 120 * 1000, NULL);

在服务器中创建管道后,您应该在使用之前等待此管道上的连接:https://msdn.microsoft.com/en-us/library/windows/desktop/aa365146(v=vs.85).aspx