【发布时间】:2018-02-16 09:00:35
【问题描述】:
我知道以前有人问过这个问题,但我找不到答案,所以我发帖寻求帮助。
我有一个 DLL,一旦注入到进程中,就会创建一个命名管道。管道将等待客户端连接,并将数据发送到客户端,直到客户端断开连接。
客户端,它只会连接到管道并接收数据并处理这些数据。
我的问题是,我希望能够发送超过 1 种类型的数据,例如浮点数、整数、字符串等。如何将数据重建为正确的数据(浮点数、整数字符串等)?
这是我的客户代码:
HANDLE hPipe;
DWORD dwWritten;
char Buffer[1024];
hPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe != INVALID_HANDLE_VALUE)
{
WriteFile(hPipe,
Buffer, //How do I put all the data into a buffer to send over to the client?
sizeof(Buffer), // = length of string + terminating '\0' !!!
&dwWritten,
NULL);
CloseHandle(hPipe);
}
服务器:
wcout << "Creating Pipe..." << endl;
HANDLE hPipe;
char buffer[1024];
DWORD dwRead;
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
1,
1024 * 16,
1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
while (hPipe != INVALID_HANDLE_VALUE)
{
if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
/* add terminating zero */
buffer[dwRead] = '\0';
/* do something with data in buffer */
printf("%s", buffer);
}
}
DisconnectNamedPipe(hPipe);
}
我的问题是,我有一堆数据想一次性发送给客户端,其中可能包含 float、int、double 等内容。一旦我从服务器收集了所有数据,我会喜欢将它发送给客户端并让客户端通过像这样拆分数据来解析它:
void split(const string& s, char c,
vector<string>& v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j - i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
我对如何将所有数据发送到客户端并正确获取原始值有点迷茫?
【问题讨论】:
-
您的代码不完整;特别是,它似乎缺少一个
main()函数和至少一个#include。请edit您的代码,这是您的问题的minimal reproducible example,然后我们可以尝试重现并解决它。您还应该阅读How to Ask。 -
我只发布了我正在使用的函数,如果需要,我可以添加 main() 函数和#include。