不能这样做:NodeJS服务器创build号码,通过JSON发送给客户端

我的问题:

服务器生成一个随机数并通过JSON发送给客户端。 当我在不同的窗口上打开客户端,它显示相同的号码。 如果我点击一个刷新button,这个数字会在两个客户端上立即改变。

我是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/"); 

一些解释( 阅读代码中的评论

 //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/");