我使用套接字客户端发送http请求,一切正常,但是有些时候,某些主机返回奇怪/错误的数据。例如:
HTTP/1.1 200 OK
Date: Tue, 12 May 2020 23:19:07 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.6
X-Powered-By: PHP/7.2.6
Transfer-Encoding: chunked
Content-Type: application/json
2322
{"content_type":"application/json","response":{"datetime":"2020-05-13 02:19:07","result":0,"signature":""}}
0
正确的数据是:
HTTP/1.1 200 OK
Date: Tue, 12 May 2020 23:19:07 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.6
X-Powered-By: PHP/7.2.6
Transfer-Encoding: chunked
Content-Type: application/json
{"content_type":"application/json","response":{"datetime":"2020-05-13 02:19:07","result":0,"signature":""}}
如果使用POSTMAN,我会得到它。从主机接收数据,我使用代码:
int len = 512;
char buf_new[1000000];
buf_new[0] = '\0';
do {
len = recv(socket, buf_new, 512, 0);
buf_new[len] = 0;
Result += buf_new;
buf_new[0] = '\0';
} while (len > 0);
如果有人知道是什么问题,请帮助,谢谢!
一旦收到此错误,您需要等待其他数据的到达。您可以通过几种方式来做到这一点:
使用select / poll / epoll等特殊功能,或者如果需要跨平台代码,请使用libevent https://libevent.org。>
请稍等片刻,然后尝试重新录制如果需要减少延迟,请选择/轮询/ epoll。睡眠更容易实现。
此外,您还需要考虑TCP是流协议,并且不保留数据包成帧。亲切的问候,亚历克斯