I'm testing out Socket.IO for a new project that uses Compound.js (built on node.js/Express.js), but I've come across a problem. I've managed to get the basics working and the following message works fine:
Server-side JS (applicationname/config/initializers/socketio.js):
var sio = require('socket.io');
var http = require('http');
var activeClients = 0;
module.exports = function (compound) {
var app = compound.app;
var server = http.createServer(app);
compound.server = server;
var io = compound.io = sio.listen(server);
io.sockets.on('connection', function (socket) {
activeClients +=1;
var connections = setInterval(function () {
socket.emit('news', { clients: activeClients });
}, 1000);
socket.on('disconnect', function () {
activeClients -= 1;
io.sockets.emit('user disconnected');
clearInterval(connections);
});
});
}
Front-end JS (applicationname/public/index.html):
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
function msgReceived(msg){
$clientCounter.html(msg.posts);
}
$(document).ready(function () {
$clientCounter = $("#client_count");
socket.on('news', function (data) {
msgReceived(data);
socket.emit('my other event', { my: 'data' });
});
});
</script>
What I'm trying to do now is get the number of posts that have been made on the server. I used a default scaffold to generate the Posts method, controller and views.
How do I now find the total number of posts and pass that value to the server-side JS?
Simply count the number of emits on the server side and send that?
...
var emits = 0;
var connections = setInterval(function () {
emits++;
socket.emit('news', { clients: activeClients , num_messages: emits});
}, 1000);
...
Or create a specific message that can be polled from the client