简体   繁体   English

socket.io 不刷新数据

[英]socket.io is not refreshing data

I am trying to display filesize on with socket.io with every time file changes.我试图在每次文件更改时使用 socket.io 显示文件大小。 Here is my js code.这是我的js代码。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
    res.sendfile('index.html');
});
var fs = require("fs");
var filesize;
var filename = 'D:\\test.txt';

fs.watchFile(filename, function() {
    fs.open(filename, 'r', function(err, fd) {
        fs.stat(filename, function(err, stat) {
            if(err) { console.log('error');  }
            console.log(stat.size);
            filesize = stat.size;
        });
    })
});

io.on('connection', function(socket){
    console.log('A user connected');
    socket.emit('testerEvent', { description: prntarr});
    socket.on('clientEvent', function(data){
        console.log(data);
    });
    socket.on('disconnect', function () {
        console.log('A user disconnected');
    });

});

http.listen(3000, function(){
    console.log('listening on localhost:3000');
});

The problem is , socket is not refreshing data but console shows changed size.问题是,套接字未刷新数据,但控制台显示大小已更改。 It refreshes only when i reload the page.它仅在我重新加载页面时刷新。 Please suggest where i am making mistake and how to fix it.请建议我在哪里出错以及如何解决它。

thanks in advance.提前致谢。

You need to do a socket.emit() inside your fs.watchFile() callback.您需要在fs.watchFile()回调中执行socket.emit() You're not emitting anything when the file changes at the moment当前文件更改时,您没有发出任何内容


  • When a user connects, push his socket in an Array.当用户连接时,将他的socket推入一个数组中。
  • Inside the watchFile callback, iterate through the connected sockets Array and .emit() what you want to send.watchFile回调中,遍历连接的套接字 Array 和.emit()想要发送的内容。
  • Don't forget to remove from that Array any sockets that have disconnected不要忘记从该阵列中删除任何已断开连接的sockets

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM