到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(我正在使用的)默認是持久的。你建議使用還是不使用持久性? –