Skip to content

Instantly share code, notes, and snippets.

@vordan
Forked from kixxauth/long-polling.html
Created November 20, 2021 08:43
Show Gist options
  • Save vordan/ecb2e602657f12daa1d4edd0197e57f7 to your computer and use it in GitHub Desktop.
Save vordan/ecb2e602657f12daa1d4edd0197e57f7 to your computer and use it in GitHub Desktop.
A Node.js http long polling server for HTTP streaming.
<!DOCTYPE html>
<html>
<style type="text/css">
body {
font-size: 18px;
background: #000;
color: #fff;
}
#container {
width: 600px;
margin: 100px auto;
}
</style>
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head><body>
<div id="container">
<h1>Demo</h1>
<h2>Results will appear here:</h2>
<ul id="results">
</ul>
</div>
<script>
$.ajaxSetup({headers: {'x-stream': 'rockon'}});
$(function ($) {
function longPoll () {
$.get('http://localhost:8080', function (data) {
console.log(data);
$('<li>' + data + '</li>').appendTo('#results');
longPoll();
});
}
longPoll();
});
</script>
</body>
</html>
var http = require('http');
var fs = require('fs');
var handleStatic, handleStream;
// An array where we will keep pointers to all our connections.
var connections = [];
// Main HTTP request handler
function handler(req, res) {
// If we get our custom header, do streaming, if not; return the html file.
if (req.headers['x-stream'] === 'rockon') {
return handleStream(req, res);
}
handleStatic(req, res);
}
// Return the html file
handleStatic = function (req, res) {
// Asynchronous file read.
fs.readFile('./long-polling.html', 'utf8', function (err, data) {
if (err) throw err;
// If there is no error, send the contents of the html file as the HTTP body
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
}
// Handle a long polling request
handleStream = function (req, res) {
// Don't respond the the request, just stash it in the array.
connections.push(res);
// Notice that our array will eventually blow out through memory because it never
// is pruned, and keeps a pointer to every connection ever made to this server.
}
var server = http.createServer(handler);
process.stdin.resume();
process.stdin.setEncoding('utf8');
// When input on stdin is observed, send it to each of the connected clients.
process.stdin.on('data', function (data) {
connections.forEach(function (res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
});
});
// Fire up the server
server.listen(8080, 'localhost', function () {
console.log('server running');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment