gpt4 book ai didi

c - 如何在Windows中随时(同时)发送数据?

转载 作者:行者123 更新时间:2023-11-30 14:43:02 25 4
gpt4 key购买 nike

我想在windows操作系统中编写一个namedpipe客户端,即使客户端正在接收数据,它也可以随时发送数据。 Example MSDN的只显示接收数据后发送数据。并且串行操作不是我想要的。因为我在客户端和服务器之间传输的数据不是很大,也就是说IO操作应该不是一个耗时的过程,所以我在客户端没有使用OVERLAP

我在MSDN客户端示例中修改的代码如下:主线程不断读取数据,子线程不断向服务器发送数据。但调试时读取数据时服务器阻塞。

std::thread t([&] {
cbToWrite = (lstrlen(lpvMessage) + 1) * sizeof(TCHAR);
_tprintf(TEXT("Sending %d byte message: \"%s\"\n"), cbToWrite, lpvMessage);


fSuccess = WriteFile(
hPipe, // pipe handle
lpvMessage, // message
cbToWrite, // message length
&cbWritten, // bytes written
NULL); // not overlapped

if (!fSuccess)
{
_tprintf(TEXT("WriteFile to pipe failed. GLE=%d\n"), GetLastError());
return -1;
}

printf("\nMessage sent to server, receiving reply as follows:\n");

});

while (1) // main thread always reading
{
do
{
// Read from the pipe.

fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE * sizeof(TCHAR), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped

if (!fSuccess && GetLastError() != ERROR_MORE_DATA)
break;

_tprintf(TEXT("\"%s\"\n"), chBuf);
} while (!fSuccess); // repeat loop if ERROR_MORE_DATA

if (!fSuccess)
{
_tprintf(TEXT("ReadFile from pipe failed. GLE=%d\n"), GetLastError());
return -1;
}
}


t.join();

我希望有人可以更正该代码以使其正常工作,或者您能告诉我标准做法或建议吗?非常感谢!

最佳答案

来自CreateFile关于FILE_FLAG_OVERLAPPED

的文档

If this flag is specified, the file can be used for simultaneous read and write operations.

If this flag is not specified, then I/O operations are serialized

I/O 操作是序列化的,意味着新的 I/O 请求将等待,直到先前的 I/O 请求未完成。因此,如果您不使用 FILE_FLAG_OVERLAPPED ,即使在这里使用多个线程也无济于事。例如,您可以从一个线程开始读取操作并等待,直到数据不存在。如果您从另一个线程调用此文件的 write - write 将在 I/O 子系统代码中等待,直到您的读取未完成。即使您说查询文件名(通过 GetFileInformationByHandleExFileNameInfo),此请求也会被序列化并等待您的读取未完成。

因此,在创建文件时,同时 I/O 操作(不仅是读写,而是所有操作)的唯一选项使用 FILE_FLAG_OVERLAPPED

关于c - 如何在Windows中随时(同时)发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54169937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com