我有一个用Javascript编写的客户端应用程序,它与节点服务器进行通信,如下所示:
// event listener for the listen button click
document.getElementById("Start").addEventListener("click", function(){
// only do stuff if we haven't already started
if(!started){
// instantiate HTTP request to send to the server
var xmlhttp = new XMLHttpRequest();
var getString = "http://127.0.0.1:3000/?type=start&port="+PORT;
console.log(getString);
// send it away
xmlhttp.open("GET", getString, true);
xmlhttp.send();
// start some other process on the client side
startProcess();
// set the listening flag
started = true;
}
});
// event listener for the stop button click
document.getElementById("Stop").addEventListener("click", function(){
// only do stuff if we're currently listening
if(started){
// we're stopped now
started = false;
// stop the client process
stopProcess();
// send another request to the server to stop whatever's going on there
var xmlhttp = new XMLHttpRequest();
var getString = "http://127.0.0.1:3000/?type=stop";
xmlhttp.open("GET", getString, true);
xmlhttp.send();
}
});
在服务器上,我使用的是Express,只需
var express = require('express');
var app = express();
app.get('/', function(req, res){
// do some stuff to handle the request
var type = req.query.type;
if(type == 'start'){
var port = req.query.port;
// do some stuff
}else if(type == 'stop'){
// do some other stuff
}
});
var server = app.listen(3000, function(){});
但我也尝试过使用Node的HTTP并得到完全相同的结果,所以这个问题可能与Express无关。问题是当我启动服务器并打开客户端应用程序的实例并单击"开始,"一切正常。然后,当我点击"停止,"一切正常。但是,如果我尝试点击"开始"再次在客户端应用程序的同一个实例中,没有任何反应。从客户端看来,HTTP请求正在发送 - 但是,服务器永远不会收到它,因为从不调用app.get回调。我对HTTP的东西很缺乏经验,所以我有一种模糊的怀疑,我误解了一些基本的东西,但到目前为止我还没弄清楚。