【发布时间】:2019-11-27 16:04:04
【问题描述】:
我正在做一个简单的客户端服务器管道示例作为练习。服务器将使用命名管道从客户端接收字符串。服务器将反转从客户端接收到的字符串中每个字符的大小写,并使用管道将字符串发送回客户端。它有效,但我写入管道的字符串似乎被空格打断了。附上一张图片显示了我的问题。
我在服务器上创建一个这样的命名管道。
HANDLE pipe_handle = CreateNamedPipe(
PIPE_REV_NAME, //name
PIPE_ACCESS_DUPLEX, //openMode
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, //Pipe Mode
1,//Max Instances
1024,//OutBuffSize
1024,//InBuffSize
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
并像这样在服务器上读写它:
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);
【问题讨论】:
-
请不要发布可以像文本一样容易发布的输出截图/图像。
-
如果要发送字节流(而不是字符串),则读取/发送字节流而不是字符串。不要使用解释字节的函数。
-
虽然感谢您填写替代文本,至少
-
显示读取输入数据以发送,然后实际发送的循环。后者我们有一个想法,但前者是关键。就目前而言,没有minimal reproducible example,我们需要一个,否则我们只是在猜测。我的猜测:您应该使用
std::getline来读取您的字符串,然后发送 that;不通过operator >>使用格式化提取。现在,通过更新您的问题来显示相关代码。
标签: c++ operating-system pipe