Javascript 到套接字服务器连接
我想创建一个网络聊天。有人建议我使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种解决方案是长轮询。客户端将向脚本打开一个 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.
您已经了解了客户端发起的通信的想法,这非常适合从客户端向服务器发送内容。
由于 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.