2016-03-17 20 views
6

Sto usando express-ws https://www.npmjs.com/package/express-ws (API che aiuta a creare server per client express e websocket).express-ws come controllare periodicamente un evento personalizzato e agire automaticamente

app.ws('/', function(ws, req) { 
    console.log("New connection") 
    if (content.length > 0) { 
    console.log(content) 
    ws.send(content) 
    } 
    ws.on('message', function(msg, flags) { 
    console.log("Received "+ msg); 
    }); 
    ws.on('data', function(msg, flags) { 
    var data = []; // List of Buffer objects 
    res.on("data", function(chunk) { 
     data.push(chunk); // Append Buffer object 
     console.log(data) 
    }) 
    }) 
}); 

Ora, come si può vedere con il codice di cui sopra, ogni volta che viene creata una connessione controlla la lunghezza dei contenuti e lo invia al cliente conetent se più di 0.

seguito il codice del router, su richiesta web, aggiorna la file. Problema con questo se qualche tempo dopo la creazione della connessione se questo file è stato modificato, questa connessione non è al corrente e quindi la funzione di invio non viene chiamata. Ho anche provato fs.watch ma non sono in grado di farlo funzionare.

router.post('/run_restart', function(req, res, next) { 
    text = '{"to_do": "run_test", "devices":"all", "argv": { "test": "' + req.body.cmd + '", "cycles": "' + req.body.cycles + '", "awake_for": "' + req.body.wt + '" }}' 
    path = process.env['HOME']+'/Desktop/automation/Stressem/StressemWeb/bin/task.txt' 
    fs.writeFile(path, text) 
    res.render('home.jade', { title: 'Stressem' }); 
}); 

fs.watch(file, function (event) { 
    fs.stat(file, function (err, stats) { 
    if(stats.size>80){ 
     console.log("Event: " + event); 
     fs.readFile(file, 'utf8', function (err, data) { 
     if (err) throw err; 
     content = data.toString(); 
     }); 
    } 
    }); 

Quello che vorrei è ogni volta che il file viene aggiornato, ws.send può essere chiamato per uno della connessione websocket.

risposta

2

risolto questo con qualcosa di simile

var conn_array = []; 
app.ws('/', function(ws, req) { 
    conn_array.push(ws) 
    console.log("New connection") 

    fs.readFile(file, 'utf8', function (err, data) { 
     if (err) throw err; 
     content = data.toString(); 
     if (content.length > 0) { 
      console.log(content.length) 
      conn_array[0].send(content) 
     } 
    }); 


    ws.on('message', function(msg, flags) { 
     console.log("Received "+ msg); 
    }); 

    ws.on('data', function(msg, flags) { 
     var data = []; // List of Buffer objects 
     res.on("data", function(chunk) { 
      data.push(chunk); // Append Buffer object 
      console.log(data) 
     }) 
    }) 
}); 

function readFile(){ 
    console.log("I am here") 
    fs.readFile(file, 'utf8', function (err, data) { 
     if (err) throw err; 
     content = data.toString(); 
     if (content.length > 0 && conn_array.length>0) conn_array[0].send(content); 
    }) 
} 

var interval = setInterval(readFile, 100000); 

per ora ho assunto non v'è solo un cliente

2

Questo semplice codice funziona bene con Express. Se qualche ritardo non è un problema per te, puoi usare questo.

setInterval(milisecondsToCheck, checkFunction) 

per più

http://www.w3schools.com/jsref/met_win_setinterval.asp

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

se lo si utilizza in questo modo, si può finire dopo che il lavoro fatto:

var timer = setInterval(milisecondsToCheck, checkFunction); 

per cancellarlo:

clearInterval(timer); 
+0

Grazie per voi rtime guardare in questo. Ma il problema rimane lo stesso. Come posso chiamare questa funzione per una connessione particolare? –

+0

controlla questo http://stackoverflow.com/questions/9935920/how-to-write-a-node-js-function-that-waits-for-an-event-to-fire-before-returnin – bmavus

4

Poiché il server è quello che cambia il file, non è necessario utilizzare fs.watch come già sapete quando un file cambia. Tutto ciò che resta da fare è iterare su un elenco di connessioni aperte e inviare loro i nuovi contenuti.

var connections = []; // Keeps track of all connections 
app.ws('/', function(ws, req) { 
    console.log("New connection") 
    connections.push(ws); // Add the new connection to the list 

    if (content.length > 0) { 
    console.log(content) 
    ws.send(content) 
    } 
    ws.on('message', function(msg, flags) { 
    console.log("Received "+ msg); 
    }); 
    ws.on('data', function(msg, flags) { 
    var data = []; // List of Buffer objects 
    res.on("data", function(chunk) { 
     data.push(chunk); // Append Buffer object 
     console.log(data) 
    }) 
    }) 
    // TODO: Make sure you remove closed connections from `connections` 
    // by listening for the ws `close` event. 
}); 

router.post('/run_restart', function(req, res, next) { 
    text = '{"to_do": "run_test", "devices":"all", "argv": { "test": "' + req.body.cmd + '", "cycles": "' + req.body.cycles + '", "awake_for": "' + req.body.wt + '" }}' 
    path = process.env['HOME']+'/Desktop/automation/Stressem/StressemWeb/bin/task.txt' 
    fs.writeFile(path, text) 
    res.render('home.jade', { title: 'Stressem' }); 

    connections.forEach(function(c){ 
    c.send(text); // Send the new text to all open connections 
    } 
}); 

Si prega di notare: questo non funzionerà se si dispone di più processi o server, ma dal momento che si sta scrivendo per il file system locale invece di un database, Presumo che ciò non è un requisito.