Javascript 到套接字服务器连接

发布于 2024-09-11 04:01:47 字数 191 浏览 10 评论 0原文

我想创建一个网络聊天。有人建议我使用 Php 套接字服务器。我已经制作了一个,它们在 telnet 客户端上运行良好。
我发现自己困惑的是如何通过 ajax 将数据发送给客户端(没有页面刷新)。
我能想到的就是使用ajax调用php文件,获取数据并更新页面。但反过来就不行了。
或者我错过了什么?

您将如何实现一对一的网络聊天?

I wanted to create a web chat. It was suggested that i use Php Socket Servers. I've made one and they function well with a telnet client.
What i find myself bamboozled by is how to get that data to the client via ajax (no page refreshes).
All I can come up with is calling a php file with ajax, getting the data and updating the page. But that will not work the other way around.
Or am i missing something?

How would you implement a 1 on 1 web chat?

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

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

发布评论

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

评论(2

羁〃客ぐ 2024-09-18 04:01:47

一种解决方案是长轮询。客户端将向脚本打开一个 AJAX 请求,该脚本将阻塞并等待数据进入。如果一分钟内没有数据进入,它将返回,客户端将重新打开连接。如果有数据进来,那么它将立即返回数据,并且客户端将更新其视图。

要发送数据,只需执行普通的 AJAX 回调即可。

One solution is long-polling. The client will open up an AJAX request to a script that will block and wait for data to come in. If no data comes in within a minute, it will return and the client will reopen the connection. If data comes in, then it will immediately return the data and the client will update its view.

For sending the data, just do a normal AJAX callback.

笑脸一如从前 2024-09-18 04:01:47

您已经了解了客户端发起的通信的想法,这非常适合从客户端向服务器发送内容。

由于 HTTP 的无状态性质,无法将数据未经请求地“推送”到客户端。

解决这个问题的方法是始终保持与服务器的连接打开。该请求处于待处理状态,当服务器有话要说时,它会响应待处理的请求。每当发生这种情况时,客户端都会创建一个新的请求以保持不变,直到下次必须发生服务器->客户端通信为止。

实现近实时通信的另一种方法是通过频繁轮询。但我真的不推荐这种方法。特别是对于聊天程序来说更是如此。

You've got the idea of client-initiated communication, which is fine for sending things from the client to the server.

As a consequence of the stateless nature of HTTP, there is no way to "push" data, unbidden, to the client.

The way you get around this is by always leaving a connection back to the server open. The request is pending, and when the server has something to say, it responds to the pending request. Whenever this happens, the client creates a new request to leave sitting until the next time server->client communication must happen.

Another way to implement near-real-time communication is through frequent polling. But I don't recommend this approach, really. Especially not for a chat program.

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