From fe2f6ec6c48b74dd72709f52299eb86e06208e75 Mon Sep 17 00:00:00 2001 From: Manuel Araoz Date: Thu, 31 Jul 2014 16:07:14 -0300 Subject: [PATCH] add example of websocket API use --- app/controllers/socket.js | 14 ++++++- examples/messages.html | 78 +++++++++++++++++++++++++++++++++++++++ lib/MessageDb.js | 1 + 3 files changed, 91 insertions(+), 2 deletions(-) create mode 100644 examples/messages.html diff --git a/app/controllers/socket.js b/app/controllers/socket.js index 04521a9..71e7be0 100644 --- a/app/controllers/socket.js +++ b/app/controllers/socket.js @@ -3,13 +3,20 @@ // server-side socket behaviour var ios = null; // io is already taken in express var util = require('bitcore').util; +var mdb = require('../../lib/MessageDb').default(); module.exports.init = function(io_ext) { ios = io_ext; ios.sockets.on('connection', function(socket) { socket.on('subscribe', function(topic) { + console.log('subscribe ' + topic); socket.join(topic); }); + socket.on('message', function(m) { + mdb.addMessage(m.payload, m.from, m.to, function(err) { + if (err) throw err; // TODO: handle + }); + }); }); }; @@ -54,9 +61,12 @@ module.exports.broadcastSyncInfo = function(historicSync) { }; module.exports.broadcastMessage = function(from, to, ts, message) { - console.log('sending socket: %s, %s, %s, %s', from, to, ts, JSON.stringify(message)); if (ios) { - ios.sockets.in(to).emit(from + '-' + ts, message); + console.log('sending message '+to); + ios.sockets.in(to).emit(from, { + payload: message, + ts: ts + }); } } diff --git a/examples/messages.html b/examples/messages.html new file mode 100644 index 0000000..2130fd2 --- /dev/null +++ b/examples/messages.html @@ -0,0 +1,78 @@ + + + + + Socket.IO chat + + + + + +
+ + +
+ + + + + + diff --git a/lib/MessageDb.js b/lib/MessageDb.js index f1b701e..b4a4f40 100644 --- a/lib/MessageDb.js +++ b/lib/MessageDb.js @@ -59,6 +59,7 @@ var messageKey = function(from, to, ts) { }; MessageDb.prototype.addMessage = function(m, from, to, cb) { + console.log('adding message'); var key = messageKey(from, to); var value = m; this.db.put(key, value, cb);