我应该如何干净地摆脱recv循环?
我在循环中使用 recv
函数来接收网络数据,但假设我想在循环中停止接收数据。我可以打破循环,但这似乎不是停止接收数据的一种非常干净的方法。
那么有没有什么方法可以完全停止接收数据,或者只是打破循环就可以了?这是 HTTP GET/POST 请求。
这是我正在使用的简化:
do {
nDataLen = recv(mySocket, data, BUFFSIZE, 0);
if (nDataLen > 0)
{
/* Process Data */
// I'd like to break out of the loop
// if something is found when processing the data
// But, I want to do this cleanly.
}
} while (nDataLen != 0);
I'm using the recv
function in a loop to receive network data, but let's say I want to stop receiving data mid-loop. I could just break the loop, but this doesn't seem like a very clean way to stop receiving data.
So is there any way to cleanly stop receiving data, or is just breaking the loop ok? It's HTTP GET/POST requests.
Here's simplifed I'm using:
do {
nDataLen = recv(mySocket, data, BUFFSIZE, 0);
if (nDataLen > 0)
{
/* Process Data */
// I'd like to break out of the loop
// if something is found when processing the data
// But, I want to do this cleanly.
}
} while (nDataLen != 0);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
打破recv循环不会关闭连接。发生的只是停止调用 recv,从而停止从套接字读取数据。来自对等方的数据仍将到达您的套接字。如果您想彻底关闭,请在套接字文件描述符上调用
close
。Breaking out of the recv loop won't close the connection. All that happens is that you stop calling recv and therefore stop reading data from the socket. Data from the peer will still be arriving on your socket. If you want to cleanly shutdown then call
close
on the socket file descriptor.跳出循环是停止调用
recv
的一种方法。另一种方法是包含一个布尔值should_stop
并在循环条件中检查它。但是,您应该接收插座中剩余的所有内容并正确关闭它。Breaking out of the loop is a way of stop calling
recv
. Another is to include a booleanshould_stop
and check for it in the loop condition. You should however receive whatever is left in the socket and properly close it.如果不需要套接字,请关闭套接字并跳出循环。
If you don't need the socket close the socket and break out of loop.