我的问题:
服务器生成一个随机数,并通过JSON将其发送给客户端。当我在不同的窗口打开客户端时,它显示相同的数字。如果我点击刷新按钮,则两个客户端的数字会立即改变。
我是Javascript,Node.js等新手,因为它是我在德国担任软件工程师学生的第一个月,我只习惯使用Java(不是Javascript)和HTML。
//my server:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', 'utf-8', function (err, content) {
if (err) {
res.end('error occurred');
return;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(content);
res.end();
});
}).listen(8124);
var ranNum = '{"number": "' + parseInt(Math.random() * 100000000) + '"}';
console.log("server at http://localhost:8124/");
答案 0 :(得分:1)
一些解释(读取代码中的注释)
//my server:
var http = require('http');
var fs = require('fs');
// You create an http server <------------------------------------ this process finish here
http.createServer(function (req, res) {// instantly
// everything here happen after the end of your process |
// of http.createServer |
// |
// |
// here we have launched our server and are |
// waiting for any connection. |
// |
// |
// each a connection reach the server |
// we open a file called 'index.html' |
fs.readFile('index.html', 'utf-8', function (err, content) {// |
if (err) {// if an error occur on reading |
// we send a response to the client |
// to inform the webbrowser about the error |
res.end('error occurred');// |
return;// |
}// |
// if no error we write a response to the client |
res.writeHead(200, {'Content-Type': 'text/html'});// |
// we tell 200 everything ok |
// in the format of : 'Content-Type': 'text/html' |
res.write(content);// we insert in the response the content |
// the content of the file we have read, just now |
// |
res.end();// we send the response to the client |
});// |
}).listen(8124); // you tell the server to listen on port 8124 <----------
// ^
// |
// |-------------------|
// °
// you have to call this port (8124) from
// your webbrowser to reach the http server you just created.
// here you create a variable called ranNum
// you created this one time only
var ranNum = '{"number": "' + parseInt(Math.random() * 100000000) + '"}';
// ranNum should now be something like
// ranNum = '{"number": "37567307"}';
console.log("server at http://localhost:8124/");
// add this line to test :
console.log("ranNum : " , ranNum);
//your console will log the same thing one time only.
所以实际上要为每个客户发送不同的号码,你必须这样做:
var http = require('http');
var server = http.createServer(function(request, response) {
console.log("we have a request : " + new Date());
var ranNum = '{"number": "' + parseInt(Math.random() * 100000000) + '"}';
console.log("ranNum sent : " , ranNum);
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(ranNum);
});
server.listen(8124);
console.log("server at http://localhost:8124/");