Skip to content

Instantly share code, notes, and snippets.

@laser
Last active November 4, 2023 04:01
Show Gist options
  • Save laser/f2efdbb6a61b938d88c3 to your computer and use it in GitHub Desktop.
Save laser/f2efdbb6a61b938d88c3 to your computer and use it in GitHub Desktop.
Socket.IO + Vanilla JS
var request = require('request-json'),
express = require('express'),
app = express(),
http = require('http').Server(app),
io = require('socket.io'),
db = require('mongodb').MongoClient;
///////////////////////////////////////////////////////////
// boilerplate code: ignore
//
app.get('/', function(req, res) {
res.sendFile('./static/index.html');
});
app.post('/api/log', function(req, res) {
var x = ((Math.random() * 10) > 5) ? "NOT\nJSON" : true;
res.send(x);
});
app.get('/api/weather', function(req, res) {
res.send({
"main": {
"temp": (Math.round(Math.random() * 1000) / 10)
},
"weather": [{
"main": "Cloudy"
}]
});
});
app.use(express.static('./static'));
http.listen(3000, function() {
console.log(new Date(), 'started server');
});
io = io(http);
function getFunFact(callback) {
db.connect('mongodb://127.0.0.1:27017/library', function(err, _db) {
_db.collection('facts').findOne(callback);
});
}
///////////////////////////////////////////////////////////
// demo impl below
//
function log(id, messages, callback) {
function attempt(retries) {
request
.newClient('http://localhost:3000/api/')
.post('log', { messages: messages }, function(err, response) {
if (!err) callback(err, response);
else {
if (retries < 0) callback(err, response);
else {
setTimeout(function() {
attempt(retries-1);
}, 100);
}
}
});
}
attempt(10);
}
var messages = [];
io.on('connection', function(socket) {
socket.broadcast.emit('message', 'CONN: ' + socket.id);
socket.on('message', function(msg) {
io.emit('message', socket.id + ': ' + msg);
if (messages.push(msg) === 20) {
getFunFact(function(err, fact) {
if (err) throw err;
io.emit('message', 'Did you know that: ' + fact.text);
});
log(socket.id, messages, function(err) {
if (err) throw err;
// otherwise OK
});
messages = [];
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment