最近在网上找到了一份php+ajax连实现comet的实例,但是我演示的时候只是实现了其中的一个客户端,怎么同时实现两个客户端之间的通信呢?
解决方案 »
- 求助:Warning: imagettfbbox() [function.imagettfbbox]: Invalid font filename
- 帮我看看这句insert语句有什么错?
- PHP截取从数据库中读出的数据
- Can't modify header information 这个bug怎么改?
- PHP读取目录含特殊字符会变成?,如何将让MYSQL正确显示插入的UTF8编码数据
- excel转换成csv文件 问题。。。急!!!请高手帮忙
- 请问:小弟能加各位高手的QQ?MSN来聊聊吗?向你们学习一下!愿意的进
- 怎么来写文章页的内翻页,能提供代码
- 各位看一下这个问题
- getjson调用问题请高手看看
- memcache缓存的疑问
- 如何同步不同库不同表,中的字段信息?mysql
comet 总是下行的,客户端发出的信息需要通过另外的渠道
这样,由 comet 触发的 php 程序并不能直接收到额外的用户信息。需要在服务端轮询公共资源获取
<?php$filename = dirname(__FILE__).'/data.txt';// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
file_put_contents($filename,$msg);
die();
}// infinite loop until the data file is not modified
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
usleep(10000); // sleep 10ms to unload the CPU
clearstatcache();
$currentmodif = filemtime($filename);
}// return a json array
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();?>
<div id="content">
</div><p>
<form action="" method="get" onsubmit="comet.doRequest($('word').value);$('word').value='';return false;">
<input type="text" name="word" id="word" value="" />
<input type="submit" name="submit" value="Send" />
</form>
</p><script type="text/javascript">
var Comet = Class.create();
Comet.prototype = { timestamp: 0,
url: './backend.php',
noerror: true, initialize: function() { }, connect: function()
{
this.ajax = new Ajax.Request(this.url, {
method: 'get',
parameters: { 'timestamp' : this.timestamp },
onSuccess: function(transport) {
// handle the server response
var response = transport.responseText.evalJSON();
this.comet.timestamp = response['timestamp'];
this.comet.handleResponse(response);
this.comet.noerror = true;
},
onComplete: function(transport) {
// send a new ajax request when this request is finished
if (!this.comet.noerror)
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){ comet.connect() }, 5000);
else
this.comet.connect();
this.comet.noerror = false;
}
});
this.ajax.comet = this;
}, disconnect: function()
{
}, handleResponse: function(response)
{
$('content').innerHTML += '<div>' + response['msg'] + '</div>';
}, doRequest: function(request)
{
new Ajax.Request(this.url, {
method: 'get',
parameters: { 'msg' : request }
});
}
}
var comet = new Comet();
comet.connect();
</script>
我怎么感觉这两文件只能给单一的客户端发送信息?不能同时给两个用户发送求大神指点一二。。
你所有的连接都通过这个文件交换数据当然他是用 file_put_contents($filename,$msg); 来保存最后数据的
这要的话就将其他连接产生的数据给覆盖了如果你给 file_put_contents 附加 FILE_APPEND 的话,就不会覆盖已有的数据
从而达到信息共享的目的
你只需有选择的发送其中的数据片段就可以了。这只是一个调度问题