背景
我正在尝试设计一种互动的课堂环境。这个房间有不同的幻灯片,一个聊天室和其他一些基本功能。
我的理解
为所有用户实时更新页面的一个确定方法是,一个人通过ajax将更改持久化到数据库,然后所有其他用户在一个时间间隔(1秒)内轮询服务器以检查更改.如果有他们的视图会被更新。
我的代码
每个房间都有一个独特的网址..。http://www.example.com/room/ajc73
用户可以使用以下代码浏览剪贴画:
showCard();
function showCard() {
$('#card-' + (cardId)).show();
}
$('#nextCard').click(function() {
nextCard();
});
$('#previousCard').click(function() {
previousCard();
});
function nextCard() {
if ($('#card-' + (cardId + 1)).length != 0) { // if there is a next card
$('#card-' + (cardId)).hide(); // hide current card
cardId++; // increment the card id
$('#card-' + (cardId)).show(); // and show the next card
location.hash = cardId;
}
}
function previousCard() {
if (cardId != 1) { // if we are not at the first card
$('#card-' + (cardId)).hide(); // hide the current card
cardId--; // decrement the card id
$('#card-' + (cardId)).show(); // and show the previous card
location.hash = cardId;
}
}
我的问题
是否需要将数据从user1持久化到数据库,以便将其调用并显示给user2 ?还是有一种方法可以删除数据库部件并将更改直接推送到浏览器?
发布于 2017-02-09 13:21:21
去找websockets。这将是一个更好的选择。因为它的实时和简单的逻辑将帮助您实现结果。如果您不确定是否能够使用websockets(比如您正在使用共享主机,并且您的提供商不允许这样或任何其他原因),那么您可以使用不同的服务,比如pusher(更容易理解),这些服务将帮助您完成您的工作,但要付出一定的代价。
发布于 2017-02-09 09:47:15
您可以使用套接字,只需向每个客户端广播任何输入。
当然,ajax和rest也可以这样做,但这会更困难,我将使用伪代码:
clients = {};
fn newclient() {
clients[client_id] = {
pool: [];
....
}
}
fn onNewMessage(newmessage) {
forEach(client, fn(c) {
c.pool.push(newmessage);
})
}
fn clientRequestNews() {
response = clients[client].pool;
clients[client].pool.length = 0;
return response;
}
这里的重点是,在服务器内存中,每个客户机都有一个条目,每个客户机都有一个池,当一个新消息被发送到服务器时,它会被推送到每个客户机的池中。当客户机询问消息时,服务器将返回客户机池,然后将清除该客户端的池。
这样你就不需要坚持了。
发布于 2017-02-09 09:29:26
使用网络套接字。请看这里
https://stackoverflow.com/questions/42132650
复制相似问题