當我使用這個 Python 腳本向我的服務器發送請求時:
import requests as r
url = "http://localhost:8070/"
response = r.get(url=url)
它發送以下請求:
GET / HTTP/1.1
Host: localhost:8070
User-Agent: python-requests/2.27.1
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
如果我理解正確,Connection: keep-alive意味著我不應該關閉客戶端套接字,因為客戶端可以再次使用它。
但是如果我不關閉客戶端套接字,Python 腳本就會卡住,直到我關閉套接字。是否有另一種方式表明請求已完成,以便 pythons 請求理解它?
如果我嘗試將請求發送到任何其他服務器,腳本幾乎會立即完成。我的猜測是在幾毫秒后使客戶端超時,例如通過使用這樣的選擇:
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
select_ret = select(this->_maxfds 1, &this->_readfds, &this->_writefds, NULL, &timeout);
現在我會在 select 回傳 0 后關閉客戶端套接字:
if (select_ret == 0) {
close(client_socket);
}
這是一種有效的方法,還是我錯過了什么?
我正在發送這樣的回復:
char *response = "HTTP/1.1 200 Ok\r\n\r\n";
send(this->_client_socket, response, strlen(response), 0)
BUT this does not terminate the python script. The python script still hangs after I execute this line of code. It only finishes when I close the socket on my side.
So how would I determine if I should close it or not? As I already said my approach was to use a timeout in case no data is getting written in to the socket from the client side.
uj5u.com熱心網友回復:
Your server's response is incomplete.
Your understanding of Connection: keep-alive in the request is correct. However, there is no Content-Length or Transfer-Encoding: chunked header present in your response, so the only way the client has to know when the response is finished is to wait for the socket connection to be closed on the server side. Read the rules outlined in RFC 2616 Section 4.4 and RFC 7230 Section 3.3.3 of the HTTP 1.1 protocol spec.
Try something more like this instead:
const char *response = "HTTP/1.1 200 Ok\r\nContent-Length: 0\r\n\r\n";
send(this->_client_socket, response, strlen(response), 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445764.html
標籤:python c http sockets select
上一篇:Gogin-從本地瀏覽器獲取資料
