我正在为一个使用 Compound.js(基于 node.js/Express.js 构建)的新项目测试 Socket.IO,但我遇到了一个问题。我已经设法使基础工作正常,以下消息工作正常:
服务器端 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);
});
});
}
前端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>
我现在要做的是获取服务器上发布的帖子数量。我使用默认的脚手架来生成 Posts 方法、控制器和视图。
我现在如何找到帖子总数并将该值传递给服务器端 JS?