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

我正试图让一个C ++应用程序知道什么时候发生特定操作。 我试图做到这一点的方式是通过命名pipe道。

我已经在C ++应用程序上设置了一个命名的pipe道服务器,这个服务器似乎正在工作(命名的pipe道被创build – 它出现在PipeList检索的列表上)以及C#应用程序中的一个命名的pipe道客户端: C#客户端代码行提供“pipe道处理尚未设置。你的PipeStream实现调用InitializeHandle吗? 错误,并且第2行引发“访问path被拒绝”exception。

我哪里错了?

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] = '\0'; //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 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