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

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

本文关键字:连接 C++ 服务器 管道 客户端      更新时间:2023-10-16

我正在尝试获取C 应用程序,以便让C#应用程序知道特定操作时。我试图这样做的方式是通过命名管道。

我已经在C 应用程序上设置了一个命名的管服务器,该应用似乎正在起作用(创建了命名的管道 - 它显示在PipeList检索到的列表中(,在C#App上检索到一个命名的管道客户端,其中它失败:C#客户端代码的第一行给出"尚未设置管道句柄。您的PipeStream实现是否呼叫initializeHandle?"错误,第2行抛出"访问路径的访问"例外。

我要去哪里?

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] = '';   //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());
}

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

首先您想阅读&amp;在管道上写入,因此要使用的标志为: 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