Last active
August 29, 2015 14:18
-
-
Save YurySolovyov/2e5956718a028ef137d2 to your computer and use it in GitHub Desktop.
Streaming XHR response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
var url = 'http://127.0.0.1:8000/'; | |
var req = new XMLHttpRequest(); | |
var updateProgress = function(e) { | |
var chunks = req.responseText.split('\n'); | |
var last_chunk = chunks[chunks.length - 1]; | |
if (last_chunk) { | |
console.log(last_chunk); | |
} | |
}; | |
req.onprogress = updateProgress; | |
req.open("GET", url); | |
req.send(); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>exp</title> | |
</head> | |
<script src="jquery-2.1.3.min.js"></script> | |
<script src="client.js"></script> | |
<body> | |
see console | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var counts_map = {}; | |
var res_map = {}; | |
var id = 0; | |
var scheduleWrite = function(req_id) { | |
setTimeout(function() { | |
var res = res_map[req_id]; | |
var count = counts_map[req_id].count; | |
if (count >= 0) { | |
res.write('foo_' + count); | |
res.write('\n'); | |
counts_map[req_id].count--; | |
scheduleWrite(req_id); | |
} else { | |
res.end('foo_last'); | |
delete counts_map[req_id]; | |
delete res_map[req_id]; | |
} | |
}, 200); | |
}; | |
http.createServer(function(req, res) { | |
res.setHeader('Access-Control-Allow-Origin', '*'); | |
res.setHeader('content-type', 'application/octet-stream'); | |
var req_id = (++id).toString(16); | |
scheduleWrite(req_id); | |
counts_map[req_id] = { count: 10 }; | |
res_map[req_id] = res; | |
}).listen(8000, function() { | |
console.log('server is listening on port 8000') | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment