Created
December 4, 2015 02:22
-
-
Save 0xKD/f3319ef301e315fcabbc to your computer and use it in GitHub Desktop.
Realtime (rethinkdb changefeeds, socket.io)
This file contains 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"> | |
<title>Loclog</title> | |
<style> | |
body, html { | |
padding: 0; | |
} | |
* { | |
-webkit-box-sizing: border-box; | |
-moz-box-sizing: border-box; | |
box-sizing: border-box; | |
} | |
#output { | |
margin-top: 2rem; | |
padding: 1rem; | |
font-family: monospace; | |
margin: 0 auto; | |
box-shadow: 0 0 2px rgba(0, 0, 0, 0.33); | |
} | |
</style> | |
</head> | |
<body> | |
<div id="output"> | |
<pre id="log">hello</pre> | |
</div> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js"></script> | |
<script type="text/javascript"> | |
window.addEventListener('DOMContentLoaded', function(evt) { | |
var socket = io(); | |
var out = document.getElementById('log'); | |
socket.on('loc_update', function(msg) { | |
out.innerHTML = out.innerHTML + '\n' + msg; | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains 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 r = require('rethinkdb'); | |
var app = express(); | |
var http = require('http').Server(app); | |
var io = require('socket.io')(http); | |
var s = { | |
init: function(connection) { | |
app.use('/static', express.static(__dirname + '/static')); | |
app.get('/foo', function(req, resp) { | |
console.log(req.query); | |
r.table('loc').insert({ | |
'position': r.point(parseFloat(req.query.lat), parseFloat(req.query.lng)) | |
}).run(connection, function(err, resp) { | |
if (err) { | |
console.log(err); | |
} | |
}); | |
resp.send('ok'); | |
}); | |
var server = http.listen(3000, function() { | |
var address = server.address().address; | |
var port = server.address().port; | |
console.log(`[+] Listening on ${address}:${port}`); | |
}); | |
r.table('loc').changes().run(connection, function(err, cursor) { | |
if (err) { | |
throw err; | |
} | |
cursor.each(function(err, resp) { | |
if (err) { | |
console.log(`[!] Error: ${err}`); | |
} else { | |
console.log(resp); | |
io.emit('loc_update', JSON.stringify(resp)); | |
} | |
}); | |
}); | |
} | |
}; | |
r.connect({host: 'localhost', port: 28015}, function(err, conn) { | |
if (err) { | |
throw err; | |
} | |
s.init(conn); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment