正在尝试从命名管道中读取。据我所知,客户端连接正常并正在发送。考虑到代码是从这里的解决方案中获取的,我很难看到我搞砸了的地方。 Readfile 似乎没有得到任何东西。它不会返回。 如果在客户端关闭连接,则返回 0。
有什么想法吗?
DWORD WINAPI LogManager::LogCollector(LPVOID args)
{
LogMan *LogMgr = (LogMan*)args;
int run; LogMgr ->GetValue(run);
while (run != LogMan::eNONE) {
HANDLE pipe = CreateNamedPipe("\\\\.\\pipe\\RCLogPipe", PIPE_ACCESS_INBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
ConnectNamedPipe(pipe, NULL);
if (pipe == INVALID_HANDLE_VALUE){
CloseHandle(pipe);
return -1;
}
char line[1024];
DWORD numRead = 0;
if (!ReadFile(pipe, line, 1024, &numRead, NULL) || numRead < 1) return -1;
LogMgr ->Write(line);
LogMgr ->GetValue(run);
CloseHandle(pipe);
}
return 0;
}
客户端
var client = new NamedPipeClientStream("RCLogPipe");
client.Connect();
StreamWriter writer = new StreamWriter(client);
if (client.CanWrite) writer.WriteLine("Hello\n");
最佳答案
C# 的 StreamWriter 可能会缓冲直到发生刷新,因此您在那里回答了自己的第一个问题。 C# 不会以 null 结尾的字符串(ReadFile 也不会 - 它不会对您正在读取的数据做出任何假设,因为它可能会关心您的数据可能是二进制的),但您正在使用您得到的数据ReadFile 就像一个 c 字符串(以 null 结尾的字符串)。所以 Write 将看到 {'h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' [任意字节]}。 Write 将继续读取内存,直到找到一个空字符,此时它停止。所以所有的垃圾都是任意垃圾,直到 Write 偶然发现一个空字符。
您需要使用 numRead 值将其传递给 Write 以告诉它要查看多少缓冲区,或者使用它手动以 null 终止您的字符串 - line[numRead] = '\0 ';
- 假设您在缓冲区中有空间。
关于c# - 命名管道消息无法通过 (Windows/C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17343825/