发出HTTP请求而无需打开新连接

如果浏览器打开了到远程服务器的连接,是否可以通过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);
         }
     }
);

这里的问题是,这打开了与设备的新连接,但是我想使用浏览器已经连接到的插座。这可能吗?如果可以,怎么办?

zydx123 回答:发出HTTP请求而无需打开新连接

浏览器内部没有应用程序控件来确定是否将新连接用于下一个请求或是否使用现有连接。实际上,浏览器将并行使用多个连接到同一服务器是完全正常的,并且您的服务器必须能够处理此问题。

由于您的服务器体系结构似乎一次只能处理一个连接,因此您需要更改体系结构以处理多个并行连接,或者确保您一次只需要处理一个连接。后者可以通过不支持HTTP保持活动来实现,即通过在每次响应后立即关闭连接来实现。这样,新请求将产生一个新的连接(根据您的问题,这不是您想要的连接),但是由于上一个连接已关闭,您的服务器也将能够处理该新连接(这可能是您最终需要的连接)

本文链接:https://www.f2er.com/3157660.html

大家都在问