我正在制作一个简单的客户端服务器管道示例作为练习。服务器将使用命名管道从客户端接收字符串。服务器将从客户端接收到的字符串中每个字符的大小写反转,并使用管道将字符串发送回客户端。它有效,但我写入管道的字符串似乎被空格打断了。附上一张显示我的问题的图片。
我在服务器上创建一个这样的命名管道。
HANDLE pipe_handle = CreateNamedPipe(
PIPE_REV_NAME,//名称
PIPE_ACCESS_DUPLEX,//开启模式
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,//管道模式
1,//最大实例数
1024,//输出缓冲区大小
1024,//输入缓冲区大小
NMPWAIT_USE_DEFAULT_WAIT,
空);
然后像这样在服务器上读写它:
DWORD bytes_read;
ReadFile(
pipe_handle,
(LPVOID)string_to_reverse,
MAX_PIPE_REVLEN - 1,
&bytes_read,
NULL);
string_to_reverse[bytes_read] = '\0';
printf("Recieved: %s\n", string_to_reverse);
cap_reverse(string_to_reverse, bytes_read);
printf("Sending: %s\n", string_to_reverse);
DWORD bytes_written;
WriteFile(
pipe_handle,
(LPVOID)string_to_reverse,
bytes_read,
&bytes_written,
NULL);
客户端像这样创建一个文件来使用管道:
HANDLE pipe_handle = CreateFile(
PIPE_REV_NAME,
GENERIC_READ | GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL
);
然后像这样读写管道:
strncpy_s(buff, toReverse.c_str(), MAX_PIPE_REVLEN - 1);
printf("Sending: %s\n", buff);
WriteFile(
pipe_handle,
(LPVOID)buff,
toReverse.length(),
&bytes_written,
NULL);
printf("Waiting\n");
DWORD bytes_read = 0;
ReadFile(
pipe_handle,
(LPVOID)buff,
toReverse.length(),
&bytes_read,
NULL);
最佳答案
这与管道无关。
从您的屏幕截图中,我们可以看到是您的客户端 一次处理了您输入的一个词。 (注意“发送:”是如何针对每个单词重复的。)
您没有向我们展示该代码,也没有向我们展示一个最小的可重现示例,但我可以看出您做了这样的事情:
std::string input;
if (std::cin >> input)
{
// send to pipe
}
不要。相反,这样做:
std::string input;
if (std::getline(std::cin, input))
{
// send to pipe
}
引用资料:
关于c++ - 为什么我的 NamedPipe 用空格分隔我的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57099262/