基于http的flash chat(实时通讯)
前两年发过基于socket的flash chat代码,但不是所有的情况都会选择(或者有条件)使用socket的服务器。基于http的实时通讯可以用在对即时性要求不是太高的程序。
原理是通过客户端获取信息的请求,如果没有需要的内容,后台程序会等待一段时间(反应速度),然后再看看有没有需要的结果。如果多次运行没有结果,返回超时信息。让客户端再次连接。
$times = 0; function read($id) { $link = getMySq(); $rs = mysql_query("select id,msg,t from c where id>".$id); //返回json格式的结果 $result = '['; $ns = true; while($row = mysql_fetch_object($rs)) { $result = $result.'{"m":"'.$row->msg.'",'.'"i":"'.$row->id.'"},'; $ns = false; } $result = $result.'{}]'; if($ns) { mysql_close($link); $times++; //5次请求也没有反应,做超时判断,让客户端重新请求 if($times >= 5) { echo '[]'; return; } //如果当前没有可读的数据,等待1秒再读,如果需要更短的时间(这样反应更快),使用usleep,单位是毫秒 sleep(1); read($id); } else { echo $result; mysql_close($link); } }

as代码:
//http://localhost/ajax/chat.php?type=r&id=1 var lv:LoadVars = new LoadVars(); lv.load('http://localhost/ajax/chat.php?type=r&id=2'); lv.onData = function(d) { trace(d) var maxid = 0; //JSON请到json.org下载 var data = (new JSON()).parse(d); // str = ''; for(var i=0;i<data.length-1;i++) { str += data[i].m+'\n'; maxid = data[i].i; } m.text += str; // m.scroll = m.maxscroll; // lv.load('http://localhost/ajax/chat.php?type=r&id='+maxid); } /// Key.addListener(this); onKeyDown = function() { if(Key.getAscii() == 13) { if(Selection.getFocus()== '_level0.smsg') sendMsg(); } } send.onPress = function() { sendMsg(); } function sendMsg() { if(smsg.text.length > 1) { var slv:LoadVars = new LoadVars(); slv.load('http://localhost/ajax/chat.php?msg='+smsg.text); smsg.text = ''; } }
flash源文件下载:http://roading.net/res/blog/pic/httpchat.fla
完整的php代码:
<?php /* 建立chat数据库 建立表: -- -- 表的结构 `c` -- CREATE TABLE `c` ( `id` int(8) NOT NULL auto_increment, `msg` varchar(200) character set utf8 default NULL, `t` smallint(2) NOT NULL default '0', PRIMARY KEY (`id`) ) ; */ $type=$_GET['type']; if($_GET['type'] == 'r') { $id = $_GET['id'] ; read($id); } else { $msg = $_GET['msg'] ; write($msg); } function write($msg) { $link = getMySq(); //如果超过20条数据,清空一下 $rs = mysql_query("select count(id) as num from c"); $row = mysql_fetch_object($rs); if($row->num > 20) { $rs = mysql_query("delete from c"); } // $rs = mysql_query("insert into c (msg,t)values('$msg',1)"); //$id = mysql_insert_id(); mysql_close($link); } // $times = 0; function read($id) { $link = getMySq(); $rs = mysql_query("select id,msg,t from c where id>".$id); // $result = '['; $ns = true; while($row = mysql_fetch_object($rs)) { $result = $result.'{"m":"'.$row->msg.'",'.'"i":"'.$row->id.'"},'; $ns = false; } $result = $result.'{}]'; if($ns) { mysql_close($link); $times++; //5请求也没有反应,做超时判断,让客户端重新请求 if($times >= 5) { echo '[]'; return; } //如果当前没有可读的数据,等待1秒再读 sleep(1); read($id); } else { echo $result; mysql_close($link); } } /// function getMySq() { $dbpw = '123456'; $dbname = 'chat'; // $link = mysql_connect("localhost", "root", $dbpw) or die("Could not connect: " . mysql_error()); mysql_select_db($dbname); return $link; } ?>



