Data Streaming con Node.js
-
23-09-2019 - |
Domanda
Vorrei sapere se è possibile lo streaming di dati dal server al client con Node.js. Voglio inviare una singola richiesta AJAX per Node.js, poi lasciare la connessione dati aperti e continuamente flusso al cliente. Il cliente riceverà questo flusso e aggiornare la pagina in modo continuo.
Aggiornamento:
Come un aggiornamento per questa risposta - non riesco a ottenere questo lavorare. Il response.write
non viene inviato prima di chiamare close
. Ho creato un programma di esempio che uso per raggiungere questo obiettivo:
Node.js:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var currentTime = new Date();
setInterval(function(){
res.write(
currentTime.getHours()
+ ':' +
currentTime.getMinutes()
+ ':' +
currentTime.getSeconds()
);
},1000);
}).listen(8000);
HTML:
<html>
<head>
<title>Testnode</title>
</head>
<body>
<!-- This fields needs to be updated -->
Server time: <span id="time"> </span>
<!-- import jQuery from google -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- import jQuery -->
<script type="text/javascript">
$(document).ready(function(){
// I call here node.localhost nginx ports this to port 8000
$('#time').load('http://node.localhost');
});
</script>
</body>
</html>
Utilizzando questo metodo non ottengo indietro nulla finché non chiamata close()
. Questo è possibile o devo andare con un lungo approccio sondaggio invece in cui io chiamo di nuovo la funzione di caricamento come uno viene in?
Soluzione
E 'possibile. Basta usare response.write () più volte.
var body = ["hello world", "early morning", "richard stallman", "chunky bacon"];
// send headers
response.writeHead(200, {
"Content-Type": "text/plain"
});
// send data in chunks
for (piece in body) {
response.write(body[piece], "ascii");
}
// close connection
response.end();
Potrebbe essere necessario chiudere e riaprire il collegamento ogni 30 secondi o giù di lì.
Modifica : questo è il codice che in realtà provato:
var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var currentTime = new Date();
sys.puts('Starting sending time');
setInterval(function(){
res.write(
currentTime.getHours()
+ ':' +
currentTime.getMinutes()
+ ':' +
currentTime.getSeconds() + "\n"
);
setTimeout(function() {
res.end();
}, 10000);
},1000);
}).listen(8090, '192.168.175.128');
ho collegato ad esso da Telnet e la sua infatti emette risposta Chunked. Ma per usarlo browser AJAX deve supportare XHR.readyState = 3 (risposta parziale). Non tutti i browser supportano questa, per quanto ne so. In modo da utilizzare meglio polling lungo (o WebSockets per Chrome / Firefox).
EDIT2 : Inoltre, se si utilizza nginx come reverse proxy per nodo, a volte vuole riunire tutti i pezzi e inviarlo a utenti in una sola volta. È necessario modificarlo.
Altri suggerimenti
Guarda Sockets.io. Fornisce HTTP / HTTPS streaming e utilizza vari mezzi per farlo:
- WebSocket
- WebSocket su Flash (+ sostegno alle politiche di sicurezza XML)
- XHR Polling
- XHR Multipart Streaming
- Per sempre Iframe
- JSONP Polling (per il dominio croce)
E! Si integra perfettamente con Node.JS. E 'anche un pacchetto di NPM.
È anche possibile abortire il ciclo infinito:
app.get('/sse/events', function(req, res) {
res.header('Content-Type', 'text/event-stream');
var interval_id = setInterval(function() {
res.write("some data");
}, 50);
req.socket.on('close', function() {
clearInterval(interval_id);
});
});
Questo è un esempio di expressjs. Credo che senza expressjs sarà qualcosa di simile.