Skip to content

Instantly share code, notes, and snippets.

@deadkff01
Created June 15, 2016 17:52
Show Gist options
  • Save deadkff01/847b1f6c84705cf9384fbfbbfb5f27db to your computer and use it in GitHub Desktop.
Save deadkff01/847b1f6c84705cf9384fbfbbfb5f27db to your computer and use it in GitHub Desktop.
Real-time example in Node.js
var express = require('express')
, app = express()
, sse = require('./sse')
var connections = []
, votes = {yes: 0, no: 0}
app.engine('jade', require('jade').__express)
app.set('view engine', 'jade')
app.use(sse)
app.get('/', (req, res) => {
res.render('vote')
})
app.get('/result', (req, res) => {
res.render('result')
})
app.get('/vote', (req, res) => {
if (req.query.yes === "true")
votes.yes++
else
votes.no++
for(var i = 0; i < connections.length; i++) {
connections[i].sseSend(votes)
}
res.sendStatus(200)
})
app.get('/stream', (req, res) => {
res.sseSetup()
res.sseSend(votes)
connections.push(res)
})
app.listen(3000, () => {
console.log('Listening on port 3000...')
})
doctype html
html
head
title Voting results for world peace
body
div(id="votes") Yes: 0, No: 0
div(id="state") Disconnected
script(src="//code.jquery.com/jquery-2.1.4.min.js")
script.
if (!!window.EventSource) {
var source = new EventSource('/stream')
source.addEventListener('message', (e) => {
votes = JSON.parse(e.data)
$("#votes").text("Yes: " + votes.yes + ", No: " + votes.no)
}, false)
source.addEventListener('open', (e) => {
$("#state").text("Connected")
}, false)
source.addEventListener('error', (e) => {
if (e.target.readyState == EventSource.CLOSED) {
$("#state").text("Disconnected")
}
else if (e.target.readyState == EventSource.CONNECTING) {
$("#state").text("Connecting...")
}
}, false)
} else {
console.log("Your browser doesn't support SSE")
}
module.exports = (req, res, next) => {
res.sseSetup = () => {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
}
res.sseSend = (data) => {
res.write("data: " + JSON.stringify(data) + "\n\n")
}
next()
}
doctype html
html
head
title Voting for the world peace
body
h1 Will "Hello, World!" bring world peace?
<div id="yes">Yes</div>
<div id="no">No</div>
<div id="message"></div>
script(src="//code.jquery.com/jquery-2.1.4.min.js")
script.
function vote(yes) {
$.get("/vote?yes=" + yes, () => {
$("#yes").hide()
$("#no").hide()
$("#message").text("Thank you for your vote!")
})
}
$("#yes").on("click", () => {
vote(true)
})
$("#no").on("click", () => {
vote(false)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment