Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created February 9, 2017 10:17
Show Gist options
  • Save CatTail/f61306efd0f90b6b50b064e72e42b012 to your computer and use it in GitHub Desktop.
Save CatTail/f61306efd0f90b6b50b064e72e42b012 to your computer and use it in GitHub Desktop.
Simple Req/Rep pattern for socket.io (which is Pub/Sub in nature)
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.2/socket.io.js"></script>
<script>
var socket = io('http://localhost:8088');
var route = createRouter((reply) => {
socket.on('rep', reply)
})
socket.emit('req', route('hello world', (data) => {
console.log(data)
}))
function createRouter(onReply) {
var seq = 0
var map = {}
function reply(message) {
map[message[0].seq](message[1])
}
function route(body, callback) {
seq++
var envelope = {seq}
var message = [envelope, body]
map[seq] = callback
return message
}
onReply(reply)
return route
}
</script>
var io = require('socket.io')();
io.on('connection', function (socket) {
socket.on('req', (message) => {
socket.emit('rep', message)
})
});
io.listen(8088);
@CatTail
Copy link
Author

CatTail commented Feb 9, 2017

The naming mostly coming from ZeroMQ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment