有从服务器发送消息到客户的另一种技术。你必须使用一个iframe来连接到一个不关闭连接的PHP脚本(或者你在服务器端使用的任何技术)。 PHP脚本随后发送JavaScript消息,每当必须向客户端通知某事时。在每条消息之后,服务器刷新输出流以强制数据真正找到到达客户端的路径,并且不会被某些输出缓冲区缓存。这是在iframe装载的PHP脚本的一个小例子代码(未测试和不完整,只是为了显示基础):
<html>
<body>
<script type="text/javascript">
function receiveMsg(data)
{
// Do something with the data, for example send it to some function
// in the parent frame (Where your chat application lives)
}
<?php
while (true) // You may also implement some abort state which should
// be checked here
{
$data = waitForData(); // This is your magic function on the server
// which waits for data to be send to the client
echo "receiveMsg('" . $data . "');"; // Let's say data is just a string.
// You may want to use JSON instead
flush();
}
?>
</script>
</body>
</html>
这种方法的优点是,它不依赖于投票。所以你不必每隔x秒就向服务器发送请求。而当你在服务器端做正确的事情时,一个用户发送的消息尽可能快地被其他用户接收,而不是在x秒后。缺点是你有每个聊天用户的永久HTTP连接。但是这可能需要较少的服务器资源,然后每个聊天用户每分钟有数十个完整的HTTP请求。
嗨,这两个链接都提供了使用只能在Google Chrome上运行的websocket的示例(截至目前,因为它是HTML5规范)。我们需要我们的应用程序在任何浏览器上运行,因此正在寻找仅使用HTML4规范和JavaScipts的选项。 – Puneet 2011-04-21 06:18:07
请看我的编辑! – 2011-04-21 06:19:31
顺便说一句,这是不正确的,websockets只能在Chrome上运行......你可以在任何webkit浏览器上运行websocket,opera 10.70 <=,firefox 4.0 beta 7 <= – 2011-04-21 06:21:47