如何使所有连接的浏览器由服务器端事件启动重新加载

发布于 2024-08-16 06:52:00 字数 154 浏览 3 评论 0原文

假设有一个包含动态生成内容的网页 - 比如说一个包含当前连接浏览器数量的 div。当服务器上的计数发生变化时,我希望所有连接的浏览器重新加载计数,以便每个人都能看到增量/减量。

实现这一目标的最佳方法是什么?

关键词:ajax、广播、浏览器、div、jquery

Suppose there is a webpage with dynamically generated content -- say a div containing the current number of connected browsers. When the count changes on the server I want all connected browsers to reload the count so that everyone sees the increment/decrement.

What's the best way to accomplish this?

Keywords: ajax, broadcast, browser, div, jquery

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

静赏你的温柔 2024-08-23 06:52:00

我认为 COMET 可能就是您正在寻找的。 Web Sockets 是理想的选择,但由于缺乏浏览器的采用,目前还无法实现。

I think COMET might be what you're looking for. Web Sockets would be ideal but lack of browser adoption wouldn't make it practical right now.

天冷不及心凉 2024-08-23 06:52:00

HTTP 协议在设计上是无状态的。实现此目的的唯一方法是通过 AJAX 实现客户端轮询。

HTTP protocol is stateless by design. The only one way to achieve this is to implement client-side polling via AJAX.

云淡风轻 2024-08-23 06:52:00

以下是如何使用 ajax 长轮询进行服务器推送。浏览器发出 ajax 请求,启动服务器端自轮询。 ajax 请求保持打开状态,等待响应,直到文件发生更改,一旦获得响应,它就会发出新的长轮询请求。

这是使用 jQuery 和 php 的效果,实现了在 html 中实时更新 div 的示例,显示了当前连接的客户端:

index.html:

<html>
<head>
<title>Comet Test</title>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="longpolling.js"></script>
</head>
<body>
  Number of connected users: <div id="total">0</div>
</body>
</html>

longpolling.js:

$(document).ready(function() { connectToServer(1); });

function connectToServer( incp ) {
  $.get("LongPolling.php",
        { inc: incp },
        function(resp) {
          $('#total').html(resp);
          connectToServer(0);
        }
       );
}

LongPolling.php:

<?php

# (over)write file with contents, locking the file while doing so.
# just barf and die if there's an error.
function update($file, $contents)
{
  $f = fopen($file, 'w');
  if(!$f) { echo "ERROR1"; exit; } # couldn't open file for writing.
  if(!flock($f, LOCK_EX)) { echo "ERROR2"; exit; } # couldn't get lock.
  fwrite($f, $contents);
  fclose($f);  # this also releases the lock.
  return $contents;
}

# fetch the contents of the given file.
# if the file doesn't exist, create it with contents "0"
function fetch($file)
{
  if(file_exists($file)) {
    if(!is_readable($file)) { echo "ERROR3"; exit; }
    $x = file_get_contents($file);
  } else {
    $x = 0;
    update($file, $x);
  }
  return $x;
}

$fc = 'connx.txt';   # file that stores the number of connections.

if ( $_REQUEST['inc'] == 1 ) {  # someone just connected.
  echo update($fc, fetch($fc)+1);
} else {  # someone is reconnecting (also happens immediately after connect).
  $last = filemtime($fc);
  do {  # wait until some other instance causes $fc to change...
    sleep(1);
    clearstatcache(); # otherwise filemtime() results are cached!
  } while(filemtime($fc) == $last);
  echo fetch($fc);
}
?>

注意:这不会跟踪断开连接,因此它更像是实时跟踪页面浏览总数。
请参阅在浏览器关闭时运行服务器端函数有关跟踪浏览器断开连接的信息,即客户端断开连接时的服务器端操作。

Here's how to do server-push using ajax long-polling. The browser makes an ajax request which initiates server-side self-polling. The ajax request remains open, waiting for a response until the file changes, and as soon as it gets a response, it makes a new long-polling request.

Here's what it looks like with jQuery and php, implementing the example of live-updating a div in the html showing the number of clients currently connected:

index.html:

<html>
<head>
<title>Comet Test</title>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="longpolling.js"></script>
</head>
<body>
  Number of connected users: <div id="total">0</div>
</body>
</html>

longpolling.js:

$(document).ready(function() { connectToServer(1); });

function connectToServer( incp ) {
  $.get("LongPolling.php",
        { inc: incp },
        function(resp) {
          $('#total').html(resp);
          connectToServer(0);
        }
       );
}

LongPolling.php:

<?php

# (over)write file with contents, locking the file while doing so.
# just barf and die if there's an error.
function update($file, $contents)
{
  $f = fopen($file, 'w');
  if(!$f) { echo "ERROR1"; exit; } # couldn't open file for writing.
  if(!flock($f, LOCK_EX)) { echo "ERROR2"; exit; } # couldn't get lock.
  fwrite($f, $contents);
  fclose($f);  # this also releases the lock.
  return $contents;
}

# fetch the contents of the given file.
# if the file doesn't exist, create it with contents "0"
function fetch($file)
{
  if(file_exists($file)) {
    if(!is_readable($file)) { echo "ERROR3"; exit; }
    $x = file_get_contents($file);
  } else {
    $x = 0;
    update($file, $x);
  }
  return $x;
}

$fc = 'connx.txt';   # file that stores the number of connections.

if ( $_REQUEST['inc'] == 1 ) {  # someone just connected.
  echo update($fc, fetch($fc)+1);
} else {  # someone is reconnecting (also happens immediately after connect).
  $last = filemtime($fc);
  do {  # wait until some other instance causes $fc to change...
    sleep(1);
    clearstatcache(); # otherwise filemtime() results are cached!
  } while(filemtime($fc) == $last);
  echo fetch($fc);
}
?>

NOTE: This does not track disconnects, so it's more like live-tracking the total number of pageviews.
See Running server-side function as browser closes for info on keeping track of browser disconnects, ie, server-side action on client disconnect.

南街女流氓 2024-08-23 06:52:00

反向 AJAX 正是您所需要的。 DWR 网页对此进行了简要说明: http://directwebremoting.org/dwr/reverse -ajax/index.html - 您可以在用于 ajax 调用的库中使用三种风格之一。

Reverse AJAX is what you need. It's briefly explained in the DWR web page: http://directwebremoting.org/dwr/reverse-ajax/index.html - you can probably use one of the three flavours with the library you are using for ajax calls.

诺曦 2024-08-23 06:52:00

截至 2014 年 12 月,W3C 提出了一项名为“服务器发送事件 (SSE)”的建议,允许您通过 HTTP 执行此操作:http://www.w3.org/TR/eventsource

看起来它是一组技术的标准化称为彗星。 (Darrel 在他的回答中链接到)

2013 年 Sinatra 的完整示例可以在以下位置找到:http://html5hacks.com/blog/2013/04/21/push-notifications-to-the-browser-with-server-sent-events /

还有一篇 2010 HTML5 Rocks 文章:http://www. html5rocks.com/en/tutorials/eventsource/basics/ ,但此后规范可能已经发生了一些变化。

当前大多数浏览器都支持此 API,但 IE11 除外: http://caniuse.com/#feat=eventsource

As of Dec 2014, there is a W3C proposed recommendation called Server Sent Events (SSE) that would allow you to do that over HTTP: http://www.w3.org/TR/eventsource

It seems that it is a standardization of a group of techniques known as Comet. (which Darrel linked to in his answer)

A full example from 2013 with Sinatra can be found at: http://html5hacks.com/blog/2013/04/21/push-notifications-to-the-browser-with-server-sent-events/

There is also a 2010 HTML5 Rocks article: http://www.html5rocks.com/en/tutorials/eventsource/basics/ , but the spec is likely t have changed a bit since.

Most current browsers support this API, with the notable exception of IE11: http://caniuse.com/#feat=eventsource

我的鱼塘能养鲲 2024-08-23 06:52:00

可以编写一个可以用作网络服务器的java小程序。一旦小程序成功启动,它就可以将其端口和 IP 号报告回远程服务器。

然后您的服务器可以随时向客户端服务器发送消息。然后,您的 Java 小程序可以将消息传递给 JavaScript,或者执行其他任何操作。

然而这种方法需要java插件支持,远非通用。

it is possible to write a java applet which can work as a network server. Once the applet has successfully started, it can report its port and ip number back to the remote server.

Then your server can send messages to the client server any time it feels like. Your java applet can then hand the message off to javascript, or do whatever else.

This method requires java plugin support however, which is far from universal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文