[英]Make HTTP requests without opening a new connection
如果瀏覽器打開到遠程服務器的連接,是否可以通過 Javascript 訪問相同的連接?
我的網絡上有一個小型以太網模塊,我的編程方式如下(偽代碼):
private var socket
while(true) {
if(socket is disconnected) {
open socket
listen on socket (port 80)
}
if(connection interrupt) {
connect socket
}
if(data receive interrupt) {
serve
}
if(disconnection interrupt) {
disconnect socket
}
}
關鍵是它在一個套接字上偵聽 HTTP 請求並為它們服務。
在我的 web 瀏覽器中,我可以連接到設備,對我編寫的一些 HTML/JS 發出 HTTP GET 請求,它可以工作。 在套接字上打開一個連接,文件作為 HTTP 響應返回。
現在我想點擊網頁上的一個按鈕,讓瀏覽器通過同一個連接發送一個 HTTP POST 請求。 在我的 Javascript 中,我有(為清楚起見進行了編輯和格式化):
// This function sends an HTTP request
function http(type, url, data, callbacks) {
// make a new HTTP request
var request = new XMLHttpRequest();
// open a connection to the URL
request.open(type, url + (data ? "?" + data : ""));
// add headers
if(type == "POST")
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// register callbacks for the request
Object.keys(callbacks).forEach(function(callback) {
request[callback] = function() {
callbacks[callback](request.responseText);
};
});
// send and return the request
request.send();
return request;
}
// Here is where I call the function
http("POST", // use POST method
"http://192.168.1.99", // IP address of the network device
dataToSend, // the data that needs to be sent
{ // callbacks
onloadend: function(data) {
console.log("success. got: " + data); // print 'success' when the request is done
},
onerror: function(data) {
console.log("There was an error."); // print 'error' when it fails
console.log(data);
}
}
);
這里的問題是這會打開一個與設備的新連接,但我想使用瀏覽器已經連接到的同一個套接字。 這可能嗎?如果可以,怎么做?
瀏覽器內部沒有應用程序控制來決定是否將新連接用於下一個請求或是否使用現有連接。 事實上,瀏覽器使用多個並行連接到同一個服務器是完全正常的,您的服務器必須能夠處理這個問題。
由於您的服務器架構似乎一次只能處理一個連接,您要么需要更改架構以處理多個並行連接,要么確保一次只需要處理一個連接。 后者可以通過不支持 HTTP keep-alive 來實現,即在每次響應后立即關閉連接。 這樣,一個新請求將導致一個新連接(根據您的問題,這不是您想要的),但是您的服務器也將能夠處理這個新連接(這可能是您最終需要的),因為前一個連接已關閉.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.