虽然循环中断,但之后的代码永远不会执行
While loop breaks but the code after it is never executed
这是while循环所在的方法。我只是连接到服务器,发送HTTP请求并读取响应。当我调试时,我仍然不明白为什么这个 while 循环没有传递。
void HttpSocket::Get(string address)
{
std::string response, host, httpRequest;
uint32_t ipAddress;
ParseRequest(address, host, httpRequest);
ResolveHostAddress(host, ipAddress);
HttpSocket::Connect(ipAddress);
strcpy(bufferToSend, httpRequest.c_str());
n = write(sockfd,bufferToSend,strlen(bufferToSend));
if (n < 0) { throw IO_Exception("Cannot send request."); }
memset(bufferToSend, 0, 500);
memset(bufferToReceive, 0, 200);
n = read(sockfd,bufferToReceive,200);
if (n <= 0){
throw IO_Exception("Cannot read response.");
}
else
{
response += bufferToReceive;
while(n != 0)
{
n = 0;
memset(bufferToReceive, 0, 200);
n = read(sockfd,bufferToReceive,200);
response += bufferToReceive;
cout << "still in the loop" << n << endl;
}
cout << "Response: " << response << endl;
}
}
顺便说一下n
volatile int
,我不认为编译器优化会导致它。仅供参考,一切都很好,一直工作到最后一个循环。
::read()
是一个同步函数。当套接字上没有任何东西可以读取时,对n = read(sockfd,bufferToReceive,200);
的调用只会挂起等待新信息的块。
要解决您的问题,您应该将套接字设置为非阻塞,并使用::recv()
读取它,如果没有可用数据,它将返回-E_WOULDBLOCK
:
#include <fcntl.h>
flags = ::fcntl(fd, F_GETFL, 0);
flags |= O_NONBLOCK;
::fcntl(fd, F_SETFL, flags);
另一种方法是在read
文件描述符之前检查可用数据:
#include <sys/ioctl.h>
int count;
::ioctl(fd, FIONREAD, &count);
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- cudaMemcpyToSymbol只是挂起,永远不会返回.GPU 处理速度为 100%.代码在 K40 上工作正常,但
- C++代码永远运行并消耗内存
- 我的程序一直在循环,永远不会"return 0;".是编译器不好还是代码不好?
- 我的C 代码永远不会超过其他语句
- if 语句"您的代码将永远不会被执行"
- 为什么我的代码永远不会重新启动命令
- 虽然循环中断,但之后的代码永远不会执行
- 永远不会达到打开枚举后的保护代码
- c++相同的代码永远不会在Visual Studio中编译/运行,有时在Qt Creator中编译/运行