到read
/write
每次调用应进行测试,并连接应在错误被重建:
在文件main.c
,而不是
//set up the connection
socket_id = get_socket();
get_ip_address("example.com");
establish_connection(socket_id);
/*...*/
//send the request
while(1) {
if(write(socket_id, request, strlen(request)) == -1 || read(socket_id, message, 1024 * 1024) == -1) {
establish_connection(socket_id);
write(socket_id, request, strlen(request));
read(socket_id, message, 1024 * 1024);
}else {
write(socket_id, request, strlen(request));
read(socket_id, message, 1024 * 1024);
}
}
你应该写类似:
/* query should be declared before this point */
while (1)
{
/* set up the connection */
socket_id = get_socket();
get_ip_address("example.com");
establish_connection(socket_id);
/* send the request */
while (1)
{
if (write(socket_id, request, strlen(request))<=0)
{
/* something goes wrong while writing, exit the inner while loop */
perror("write");
break;
}
if (read(socket_id, message, 1024 * 1024)<=0)
{
/* something goes wrong while reading, exit the inner while loop */
perror("read");
break;
}
}
/* if this point is reach, that means that one write or read call goes wrong */
close(socket_id);
}
你读过[this](https://en.wikipedia.org/wiki/HTTP_persistent_connection)吗? – jeff6times7
'write'和'read'返回的值是什么,如果失败,errno的值是多少? (提示:使用'perror()'函数) – purplepsycho
@ jeff6times7 HTTP 1.1(我正在使用的)默认是持久的。你建议使用还是不使用持久性? –