我能够通过套接字编程使用静态类成功发送数据,它适用于少量数据,但在生产环境中它会卡住一段时间,然后又开始发送数据,我无法弄清楚问题是什么?你能帮忙吗代码如下。
DWORD BytesCount;
WSABUF Buffer[1];
DWORD Flag = 0;
Buffer[0].len = SendLength;
Buffer[0].buf = SendData;
if (WSASend(*socket, Buffer, 1, &BytesCount, Flag, NULL, NULL) != SOCKET_ERROR)
{
if (BytesCount != SendLength )
Result = -2;
else
{
if (ReturnAnswer)
{
int Res = 0, recBufStart;
DWORD RecvCount = 0, AllRecv = 0;
Buffer[0].len = ReceiveLength;
Buffer[0].buf = ReceiveData;
recBufStart = 0;
saAction = saReceive;
// We need to Receive until we get all the data. When WSARecv call might only return zero bytes
bool Stop = true; // true as we dont need to recieve anything from the server.
while (!Stop)
{
Res = WSARecv(*socket, &Buffer[recBufStart], (recBufStart == 0 ? 1 : 0), &RecvCount, &Flag, NULL, NULL);
if (Res == SOCKET_ERROR)
Stop = true;
else
{
AllRecv = AllRecv + RecvCount;
if (AllRecv == ReceiveLength || RecvCount == 0)
Stop = true; // Stop
else
{
Buffer[0].buf = &ReceiveData[AllRecv];
Buffer[0].len = ReceiveLength - (AllRecv);
recBufStart = 0;
}
}
}
if (Res == SOCKET_ERROR)
Result = WSAGetLastError();
}
}
}
else
Result = WSAGetLastError();
最佳答案
我不确定这是否可能是问题所在,但从 WSASend 的 Microsoft 文档中可以看出以下内容:
When issuing a blocking Winsock call such as WSASend with the lpOverlapped parameter set to NULL, Winsock may need to wait for a network event before the call can complete.
此外,您的接收代码似乎相当复杂。在什么情况下 recBufStart 不是 0?我也不会使用变量“停止”。只需发出 break 语句即可退出 while 循环。
编辑:更仔细地查看您的接收代码,您在 while (!Stop) 之前将 Stop 设置为 true,即 while (Stop == false)。所以它不会到达 WSARecv。这是故意的吗?如果是,Microsoft 的解释和我下面的答案似乎表明您的问题,即您不断发送,Winsock 必须等待才能发送更多数据。
关于c++ - Windows 中的套接字编程发送数据会卡住一段时间并延迟一段时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7952475/