gpt4 book ai didi

javascript - 发出 HTTP 请求而不打开新连接

转载 作者:行者123 更新时间:2023-12-02 22:36:48 27 4
gpt4 key购买 nike

如果浏览器打开与远程服务器的连接,是否可以通过 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 请求并为其提供服务。

在我的网络浏览器中,我可以连接到设备,对我编写的一些 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 来实现,即在每次响应后立即关闭连接。这样,新请求将导致新连接(根据您的问题,这不是您想要的),但您的服务器也将能够处理这个新连接(这可能是您最终需要的),因为前一个连接已关闭.

关于javascript - 发出 HTTP 请求而不打开新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com