gpt4 book ai didi

c++ - WSASend 在实际向设备发送数据之前返回

转载 作者:行者123 更新时间:2023-11-28 05:48:29 25 4
gpt4 key购买 nike

抱歉,我的问题描述不当。

我的程序所做的是连接服务器、发送一些数据并关闭连接。我简化了我的代码如下:

WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

connect(s, (const sockaddr*)&dstAddr, sizeof(dstAddr));

send(s, (const char*)pBuffer, fileLen, 0);

shutdown(s, SD_SEND);
closesocket(s);

WSACleanup();

在发现导致通信关闭的 RST 之前,服务器仅接收到部分数据。

我写了一个模拟服务器程序来接受连接和接收数据,但是模拟器可以获取所有数据。因为我无法访问服务器的源代码,所以我不知道它是否有问题。有没有办法通过在客户端添加一些代码来避免这个错误,或者我可以证明服务器程序有问题吗?


设置socket的linger选项可以修复这个bug。但我需要为逗留时间的值(value)给出一个神奇的数字。

linger l;
l.l_onoff = 1;
l.l_linger = 30;
setsockopt(socket, SOL_SOCKET, SO_LINGER, (const char*)&l, sizeof(l));

最佳答案

WSASend returns before sending data to device actually

正确。

I created a non-blocking socket and tried to send data to server.

WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED)

不,你没有。您创建了一个重叠的 I/O 套接字。

After executed, returnValue was SOCKET_ERROR and WSAGetLastError() returned WSA_IO_PENDING. Then I called WSAWaitForMultipleEvents to wait for event being set. After it returned WSA_WAIT_EVENT_0, I called WSAGetOverlappedResult to get actual sent data length and it is the same value with I sent.

所以所有数据都被传输到套接字发送缓冲区。

I called WSASocket first, then WSASend/WSAWaitForMultipleEvents/WSAGetOverlappedResult several times to send a bunch of data, and closesocket at the end.

所以在该过程结束时,所有数据和关闭都已传输到套接字发送缓冲区。

But server couldn't receive all data, I used Wireshark to view tcp packets and found that client sent RST before all packet were sent out.

这可能出于多种原因,如果不查看一些代码,则无法确定。

If I slept 1 minute before calling closesocket, then server would receive all data.

同样,这取决于您的代码中还发生了什么。

It seemed like that WSASend/WSAWaitForMultipleEvents/WSAGetOverlappedResult returned before sending data to server actually.

正确。

The data were saved in buffer and waiting for being sent out.

正确。

When I called closesocket, communication was shut down.

正确。

They didn't work as my expectation.

所以你的预期是错误的。

What did I go wrong? This problem only occurred in specific PCs, the application run well in others.

没有看到一些代码就无法回答。发出 RST 的通常原因是对等方已将数据写入您已经关闭的连接:换句话说,应用程序协议(protocol)错误;但还有其他可能性。

关于c++ - WSASend 在实际向设备发送数据之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35768395/

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