如何使用长轮询(最好不用Comet或node.js)?

发布于 2024-11-28 03:37:31 字数 576 浏览 0 评论 0原文

假设我正在将存储在 localStorage 中的 HTML 页面上的文本从计算机 A 同步到计算机 B。当用户在计算机 A 上编辑文本时,我向服务器发送请求,并告诉它更改了哪些文本。有什么方法可以让服务器告诉计算机 B 有新文本,而计算机 B 不必继续检查?我读过有关 Comet 的内容,但我尝试不使用任何库。有办法吗?另外,如果您要建议 Comet,您能否给出一个使用纯 JavaScript 和 Comet 的简单示例?

我有一个想法,但不知道是否可行。在计算机 B 上,我发送一次请求,并让服务器的文件不断延迟响应,直到有一些新文本为止。这样,就像长轮询一样,但请求最终会超时。如果有办法将超时设置为永不,这会变得容易得多。那么,有人有什么想法吗?

PS-我只想使用 JavaScript 和 PHP,并尽量避免使用库。不过,如果您知道可以使用 JS 和 PHP 执行此操作的库,请无论如何告诉我。

另外,我知道曾经有过类似的问题,但我找到的答案并不令人满意。

哦,如果有人知道这里的聊天是如何进行的,你能告诉我吗?

tl;dr:我想从服务器向 HTML 页面发送请求,或者让 HTML 发送单个请求,该请求将保持活动状态,直到创建适当的响应。

Suppose I'm synchronizing text on an HTML page, stored in localStorage from computer A to computer B. When the user edits the text on computer A, I send a request to the server, and tell it what text changed. Is there any way that I can get the server to tell computer B that there's new text, without computer B having to keep checking? I've read about Comet, but I'm trying not to use any libraries. Is there a way? Also, if you're going to suggest Comet, could you give a simple example using plain JavaScript and Comet?

I had an idea, but I don't know if it'd work. On computer B, I send a request once, and let the server's file keep delaying the response till there is some new text. That way, it'd be like long-polling, but the request would eventually timeout. If there was a way to set the timeout to be never, this would get much easier. So, anyone have any ideas?

P.S.- I want to use only JavaScript and PHP and try avoid using libraries. Still, if you know of a library that can do this with JS and PHP, please tell me anyway.

Also, I know there have been questions like this, but the answers I found there weren't satisfactory.

Oh, and if anyone knows how the chat over here works, could you tell me that as well?

tl;dr: I want to send a request from a server to an HTML page, or have the HTML send a single request which is kept alive till an appropriate response is created.

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

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

发布评论

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

评论(1

白馒头 2024-12-05 03:37:31

Comet 是长轮询的实现。

问题是主机需要保持所有资源可用于所有打开的请求。必须仔细配置服务器,以使其在负载下顺利工作。这不是一个“开箱即用”的解决方案。

另一个缺点是每个用户必须绑定到特定的服务器 - 因此没有简单的方法来负载平衡请求。

坚持定期轮询通常是最好的选择。

Comet is an implementation of long polling.

The issue is the host machine needs to keep all the resources available for all of the open requests. Servers must be carefully configured to allow this to work smoothly under load. This is not an "out of the box" solution.

Another drawback is each user must be bound to a particular server - so there's no easy way to load-balance requests.

Sticking with periodic polling is often the best bet.

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