derjulezzz
derjulezzz

Reputation: 31

Can't do that: NodeJS server creates number, sends it to client via JSON

My problem:

The server generates a random number and sends it to a client via JSON. When I open the client on different windows, it shows the same number. if I click on a refresh button, the number changes instantly on both clients.

I am new to Javascript, Node.js, and so on, because its my first month as a Software Engineer student in Germany and I'm only used to Java (not Javascript) and 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/");

Upvotes: 1

Views: 67

Answers (1)

Anonymous0day
Anonymous0day

Reputation: 3042

Some explanation (read comments in code)

//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.

so in reality to send different number for each client you have to do something like that :

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

Upvotes: 1

Related Questions