我不确定您使用的是什么语言 - 我不认识这样的表达
PIPE_TYPE_BYTE OR %PIPE_WAIT OR %PIPE_READMODE_BYTE
但在我看来,服务器的 ReadFile() 应该阻塞,直到客户端写入数据。
看起来不正确(但不应该伤害任何东西)的一件事是使用NMPWAIT_USE_DEFAULT_WAIT
- 该值是供客户在调用时使用的WaitNamedPipe()
。
你能看看这 2 个 C++ 程序是否像你期望的那样交互(即,服务器阻塞直到客户端写东西)?我从 Jones/Ohlund 的“Windows 网络编程”一书中获取了这些程序。服务器ReadFile()
按预期阻止了我的调用:
- 服务器.cpp
// Server.cpp
#include <windows.h>
#include <stdio.h>
void main(void)
{
HANDLE PipeHandle;
DWORD BytesRead;
CHAR buffer[256];
if ((PipeHandle = CreateNamedPipe("\\\\.\\Pipe\\Jim",
PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1,
0, 0, 1000, NULL)) == INVALID_HANDLE_VALUE)
{
printf("CreateNamedPipe failed with error %d\n",
GetLastError());
return;
}
printf("Server is now running\n");
if (ConnectNamedPipe(PipeHandle, NULL) == 0)
{
printf("ConnectNamedPipe failed with error %d\n",
GetLastError());
CloseHandle(PipeHandle);
return;
}
if (ReadFile(PipeHandle, buffer, sizeof(buffer),
&BytesRead, NULL) <= 0)
{
printf("ReadFile failed with error %d\n", GetLastError());
CloseHandle(PipeHandle);
return;
}
printf("%.*s\n", BytesRead, buffer);
if (DisconnectNamedPipe(PipeHandle) == 0)
{
printf("DisconnectNamedPipe failed with error %d\n",
GetLastError());
return;
}
CloseHandle(PipeHandle);
}
- 客户端.cpp
// Client.cpp
#include <windows.h>
#include <stdio.h>
#define PIPE_NAME "\\\\.\\Pipe\\jim"
void main(void)
{
HANDLE PipeHandle;
DWORD BytesWritten;
if (WaitNamedPipe(PIPE_NAME, NMPWAIT_WAIT_FOREVER) == 0)
{
printf("WaitNamedPipe failed with error %d\n",
GetLastError());
return;
}
// Create the named pipe file handle
if ((PipeHandle = CreateFile(PIPE_NAME,
GENERIC_READ | GENERIC_WRITE, 0,
(LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE) NULL)) == INVALID_HANDLE_VALUE)
{
printf("CreateFile failed with error %d\n", GetLastError());
return;
}
if (WriteFile(PipeHandle, "This is a test", 14, &BytesWritten,
NULL) == 0)
{
printf("WriteFile failed with error %d\n", GetLastError());
CloseHandle(PipeHandle);
return;
}
printf("Wrote %d bytes", BytesWritten);
CloseHandle(PipeHandle);
}