无法打开管道.GLE=2

Could not open pipe. GLE=2

本文关键字:GLE 管道      更新时间:2023-10-16

我正在尝试与管道交互:C#服务器-> C++客户端

我不需要真正复杂的东西,如果服务器能够将数据发送到客户端就绰绰有余了

我不知道为什么出现此错误:无法打开管道。GLE=2

我正在使用Microsoft示例C++客户端和 C# 服务器

这就是我要做的:

C# 服务器

private void Form1_Load(object sender, EventArgs e)
{
Thread t = new Thread(Server);
t.IsBackground = true;
t.Start();
}
private void Server()
{
while (true)
{
using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("mynamedpipe", PipeDirection.Out))
{
Console.WriteLine("NamedPipeServerStream object created.");
// Wait for a client to connect
Console.Write("Waiting for client connection...");
pipeServer.WaitForConnection();
Console.WriteLine("Client connected.");
try
{
// Read user input and send that to the client process.
using (StreamWriter sw = new StreamWriter(pipeServer))
{
sw.AutoFlush = true;
sw.WriteLine("testing msg");
}
}
// Catch the IOException that is raised if the pipe is broken
// or disconnected.
catch (IOException err)
{
Console.WriteLine("ERROR: {0}", err.Message);
}
}
}            
}

C++客户端

#include <conio.h>
#include "pch.h"
#include <windows.h> 
#include <stdio.h> 
#include <tchar.h>
#include <strsafe.h>
#include "client.h"
#define BUFSIZE 512
int _tmain()
{
HANDLE hPipe;
LPCTSTR lpvMessage = TEXT("Default message from client.");
TCHAR  chBuf[BUFSIZE];
BOOL   fSuccess = FALSE;
DWORD  cbRead, cbToWrite, cbWritten, dwMode;
LPCTSTR lpszPipename = TEXT("mynamedpipe");    
// Try to open a named pipe; wait for it, if necessary. 
while (1)
{
hPipe = CreateFile(
lpszPipename,   // pipe name 
GENERIC_READ |  // read and write access 
GENERIC_WRITE,
0,              // no sharing 
NULL,           // default security attributes
OPEN_EXISTING,  // opens existing pipe 
0,              // default attributes 
NULL);          // no template file 
// Break if the pipe handle is valid. 
if (hPipe != INVALID_HANDLE_VALUE)
break;
// Exit if an error other than ERROR_PIPE_BUSY occurs. 
if (GetLastError() != ERROR_PIPE_BUSY)
{
_tprintf(TEXT("Could not open pipe. GLE=%dn"), GetLastError());
return -1;
}
// All pipe instances are busy, so wait for 20 seconds. 
if (!WaitNamedPipe(lpszPipename, 20000))
{
printf("Could not open pipe: 20 second wait timed out.");
return -1;
}
}
// The pipe connected; change to message-read mode. 
dwMode = PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState(
hPipe,    // pipe handle 
&dwMode,  // new pipe mode 
NULL,     // don't set maximum bytes 
NULL);    // don't set maximum time 
if (!fSuccess)
{
_tprintf(TEXT("SetNamedPipeHandleState failed. GLE=%dn"), GetLastError());
return -1;
}
// Send a message to the pipe server. 
cbToWrite = (lstrlen(lpvMessage) + 1) * sizeof(TCHAR);
_tprintf(TEXT("Sending %d byte message: "%s"n"), cbToWrite, lpvMessage);
fSuccess = WriteFile(
hPipe,                  // pipe handle 
lpvMessage,             // message 
cbToWrite,              // message length 
&cbWritten,             // bytes written 
NULL);                  // not overlapped 
if (!fSuccess)
{
_tprintf(TEXT("WriteFile to pipe failed. GLE=%dn"), GetLastError());
return -1;
}
printf("nMessage sent to server, receiving reply as follows:n");
do
{
// Read from the pipe. 
fSuccess = ReadFile(
hPipe,    // pipe handle 
chBuf,    // buffer to receive reply 
BUFSIZE * sizeof(TCHAR),  // size of buffer 
&cbRead,  // number of bytes read 
NULL);    // not overlapped 
if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
break;
_tprintf(TEXT(""%s"n"), chBuf);
} while (!fSuccess);  // repeat loop if ERROR_MORE_DATA 
if (!fSuccess)
{
_tprintf(TEXT("ReadFile from pipe failed. GLE=%dn"), GetLastError());
return -1;
}
printf("n<End of message, press ENTER to terminate connection and exit>");
_getch();
CloseHandle(hPipe);
return 0;
}

编辑:

已将错误打印行更改为:

std::error_code ec{ static_cast<std::int32_t>(GetLastError()), std::system_category() };
_tprintf(TEXT("WriteFile to pipe failed. GLE=%dn"));
_tprintf(ec.message().c_str);
return -1;

您在C++侧使用的管道名称不正确。应该是:"\\.\pipe\mynamedpipe"

此外,将C#面更改为以下内容:

using ( var pipeServer = new NamedPipeServerStream( "mynamedpipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message ) ) { }