我没有在客户端上实时看到带有节点js的json文件的值

时间:2018-11-27 16:24:06

标签: javascript node.js

我在此链接how to display a realtime variable in nodejs in HTML上的一个先例问题上看到了此示例,但我没有实时看到客户端上json文件的值 尽管答案定义正确。 此外,在bash中,我启动命令节点--inspect socketProva.js(socketProva.js是我的服务器文件的名称),并且在检查页面中看到此消息“预期WebSockets请求”。奇怪的是,服务器实时正确地显示了json文件的数据,但是与客户端的通信似乎没有发生。 感谢您的回答和对我英语不好的借口。

socketProva.js和index.html

var io = require('socket.io')(8080); // The port should be different of your HTTP server.
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));

io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
    console.log('new connection');

    var incremental = 0;
    setInterval(function () {
        console.log('emit new value', obj);
        obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
        socket.emit('update-value', obj); // Emit on the opened socket.
        incremental++;
    }, 1000);

});
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <p id="messages"></p> 
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <pre id="incremental"></pre>

    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
        var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.

        socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
            console.log('received new value', value);

            $('#incremental').html(value);
        });
    </script>
  </body>
</html>

JSON文件:prova.json

{
    "football":{
        "id": 1,
        "home": "Liverpool",
        "away": "Chelsea",
        "score": "1-0",
        "last scorer":"Gerrard"
    }
}

1 个答案:

答案 0 :(得分:1)

如果prova.json在一段时间内没有变化,则无需使用fs.readFileSync进行读取。您可以require

var obj = require('prova.json');

完整的示例如下所示:(记住我更改了客户端socket.io.js版本

服务器

var io = require('socket.io')();
var data = require('./data.json')

io.on('connection', function (socket) {
    console.log('connected:', socket.client.id);
    setInterval(function () {
        data.value = Math.random();
        socket.emit('update-value', data);
        console.log('message sent to the clients');
    }, 1000);
});

io.listen(8080);

客户

<!DOCTYPE html>
<html>

<head>
  <!-- this changed -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
  <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>

<body>
  <div id="incremental"></div>

  <script>
    var socket = io('http://localhost:8080');

    socket.on('update-value', function (data) {
      console.log('received new value', data);
      var $div = $('<div>');
      $div.text(data.value)
      $('#incremental').append($div);
    });
  </script>
</body>

</html>

data.json

{
    "value": 1
}