Last active
December 17, 2020 12:47
-
-
Save devshareid/9ce5bc9e937d59a35aac253f4209c611 to your computer and use it in GitHub Desktop.
Short Polling, Long Polling, Server-Sent Event, WebSocket
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<title>Short Polling Example</title> | |
</head> | |
<body> | |
<p>Status: <span class="status"></span></p> | |
<script> | |
$(document).ready(function () { | |
var status = $('.status'); | |
var poll = function() { | |
$.ajax({ | |
url: 'https://jsonplaceholder.typicode.com/todos/1', | |
dataType: 'json', | |
type: 'get', | |
success: function(data) { | |
if ( data.title ) { | |
status.text(data.title); | |
} | |
}, | |
error: function() { // error logging | |
console.log('Error!'); | |
} | |
}) | |
} | |
pollInterval = setInterval(function() { // run function every 3000 ms | |
status.text('Offline!'); | |
poll(); | |
}, 3000); | |
poll(); | |
}); | |
</script> | |
</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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<title>Long Polling Example</title> | |
</head> | |
<body> | |
<p>Status: <span class="status"></span></p> | |
<script> | |
$(document).ready(function () { | |
var status = $('.status'); | |
var poll = function() { | |
$.ajax({ | |
url: 'https://jsonplaceholder.typicode.com/todos/1', | |
dataType: 'json', | |
type: 'get', | |
timeout: 60000, | |
complete: poll, // Hit another request upon completion. | |
success: function(data) { | |
if ( data.title ) { | |
status.text(data.title); | |
} | |
}, | |
error: function() { // error logging | |
console.log('Error!'); | |
} | |
}) | |
} | |
poll(); | |
}); | |
</script> | |
</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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<title>WebSocket Example</title> | |
</head> | |
<body> | |
<p>Incoming Message: <span class="val"></span></p> | |
<script> | |
$(document).ready(function () { | |
var val = $('.val'); | |
var source = new EventSource('/stream-random-numbers'); | |
source.onmessage = function(event) { | |
val.text(JSON.parse(event.data).value); | |
}; | |
}); | |
</script> | |
</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
// Ref: https://dev.to/4shub/building-with-server-sent-events-13j | |
// Code by: Shubham Naik | |
const express = require('express'); | |
const path = require('path'); | |
const server = express(); | |
const port = 3000; | |
// create helper middleware so we can reuse server-sent events | |
const useServerSentEventsMiddleware = (req, res, next) => { | |
res.setHeader('Content-Type', 'text/event-stream'); | |
res.setHeader('Cache-Control', 'no-cache'); | |
// only if you want anyone to access this endpoint | |
res.setHeader('Access-Control-Allow-Origin', '*'); | |
res.flushHeaders(); | |
const sendEventStreamData = (data) => { | |
const sseFormattedResponse = `data: ${JSON.stringify(data)}\n\n`; | |
res.write(sseFormattedResponse); | |
} | |
// we are attaching sendEventStreamData to res, so we can use it later | |
Object.assign(res, { | |
sendEventStreamData | |
}); | |
next(); | |
} | |
const streamRandomNumbers = (req, res) => { | |
// We are sending anyone who connects to /stream-random-numbers | |
// a random number that's encapsulated in an object | |
let interval = setInterval(function generateAndSendRandomNumber(){ | |
const data = { | |
value: Math.random(), | |
}; | |
res.sendEventStreamData(data); | |
}, 1000); | |
// close | |
res.on('close', () => { | |
clearInterval(interval); | |
res.end(); | |
}); | |
} | |
server.get('/ping', function(req, res) { | |
res.send('pong!'); | |
}); | |
server.get('/', function(req, res) { | |
res.sendFile(path.join(__dirname + '/index.html')); | |
}); | |
server.get('/stream-random-numbers', useServerSentEventsMiddleware, | |
streamRandomNumbers) | |
server.listen(port, () => console.log(`Example app listening at | |
http://localhost:${port}`)); |
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<title>WebSocket Example</title> | |
</head> | |
<body> | |
<p>Status: <span class="status"></span></p> | |
<p>Incoming Message: <span class="message"></span></p> | |
<button id="ping-button">Get Random Message</button> | |
<script> | |
$(document).ready(function () { | |
var status = $('.status'); | |
var message = $('.message'); | |
var pingButton = $('#ping-button'); | |
var socket = new WebSocket("ws://localhost:3000"); | |
socket.onopen = function () { | |
status.text('Connected'); | |
} | |
socket.onmessage = function (msg) { | |
message.text(msg.data); | |
} | |
socket.onclose = function () { | |
console.log("CLOSED : ", socket.readyState); | |
} | |
$(pingButton).click(function (e) { | |
e.preventDefault(); | |
socket.send(Math.random().toString()); | |
}); | |
}); | |
</script> | |
</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 express = require('express'); | |
var path = require('path'); | |
var app = express(); | |
var expressWs = require('express-ws')(app); | |
var port = 3000; | |
app.get('/', function(req, res, next){ | |
res.sendFile(path.join(__dirname + '/index.html')); | |
}); | |
app.ws('/', function(ws) { | |
// Receive message from client | |
ws.on('message', function(msg) { | |
console.log('Message received:', msg); | |
// Send back to client | |
ws.send(msg); | |
}); | |
}); | |
app.listen(port, () => console.log(`Example app listening at | |
http://localhost:${port}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment