是否可以使用 Nodejs 和 Socket.io 更新页面的单个部分?
我正在尝试创建一个基本的节点应用程序,每次客户端连接时我都想更新页面上显示的计数器。 (我的目标是以最简单且易于学习的形式创建此应用程序,以便向我的讲师演示节点)。
服务器端应用程序片段:
建立连接
var clients = 0;
io.sockets.on('connection', function (socket) {
socket.on('connect', function () { clients += 1 });
socket.on('disconnect', function(){ clients -= 1 });
});
渲染页面
app.get(navigation.chat.page, function(req, res){
res.render('chat', {
title: navigation.chat.title,
connected: clients
});
});
聊天页面玉模板片段:
span#client_count #{connected}
| connected clients
客户端 jQuery、Socket.io 和 JavaScript
var socket = io.connect('http://localhost');
$(document).ready(function(){
socket.on('connect', socket.emit('connect'));
});
问题: 连接的客户端数量仅在页面刷新时更新。我希望该号码能够异步更新。我对 Node、socket.io 和 Express 还很陌生,所以我不确定如何解决这个问题!
I'm trying to create a basic Node application, every time a client connects I want to update the counter which is displayed on the page. (My goal is to create this application in its most simple, and learnable form to demonstrate node to my lecturer).
Server side application snippets:
Making the connection
var clients = 0;
io.sockets.on('connection', function (socket) {
socket.on('connect', function () { clients += 1 });
socket.on('disconnect', function(){ clients -= 1 });
});
Rendering the page
app.get(navigation.chat.page, function(req, res){
res.render('chat', {
title: navigation.chat.title,
connected: clients
});
});
Chat page jade template snippet:
span#client_count #{connected}
| connected clients
Client side jQuery, Socket.io and JavaScript
var socket = io.connect('http://localhost');
$(document).ready(function(){
socket.on('connect', socket.emit('connect'));
});
Problem:
The number of connected clients only updates upon page refresh. I would like the number to be updated asynchronously. I'm quite new to node, socket.io and express so i'm unsure how to tackle the problem!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
与其在客户端递增,不如在服务器端保留计数器值,在连接时递增,在断开io事件时递减。然后,您可以发送更新的计数器(在值更改的同一事件处理程序中)。在客户端,用计数器监听事件,收到后替换 html 中的值。
服务器:
客户端:
rather than incrementing on client side, better keep counter value on server side, increment on connection and decrement on disconnect io events. Then, you can send updated counter (in the same event handlers where value was changed). On client side, listen for event with counter and when received, replace value in html.
server :
client :