如果浏览器打开了到远程服务器的连接,是否可以通过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);
}
}
);
这里的问题是,这打开了与设备的新连接,但是我想使用浏览器已经连接到的插座。这可能吗?如果可以,怎么办?