码迷,mamicode.com
首页 > Web开发 > 详细

使用PHP+ajax打造聊天室应用

时间:2014-12-06 11:21:26      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   使用   sp   for   

方法1.  comet

http://www.xiumu.org/technology/the-php-notes-comet-long-connection-instance.shtml  这篇文章写的很不错,ajax保持一个与服务器的长连接,服务器阻塞直到有新的消息, 也就是说服务器需要设置最长运行时间为无限制,客户端的ajax长时间连接,直到服务器租塞完毕 ,返回结果。

浏览器端

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>Comet Test</title>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function($){
    function handleResponse(response){
    $(‘#content‘).append(‘<div>‘ + response[‘msg‘] + ‘</div>‘);
    }
 
    var timestamp = 0;
    var url = ‘./chat_backend.php‘;
    var noerror = true;
    var ajax;
 
    function connect() {
        ajax = $.ajax(url, {
            type: ‘get‘,
            data: { ‘timestamp‘ : timestamp },
            success: function(transport) {
                eval(‘var response = ‘+transport);
                timestamp = response[‘timestamp‘];
                handleResponse(response);
                noerror = true;
            },
            complete: function(transport) {
                (!noerror) && setTimeout(function(){ connect() }, 5000) || connect();
                noerror = false;
            }
        });
    }
 
    function doRequest(request) {
        $.ajax(url, {
            type: ‘get‘,
            data: { ‘msg‘ : request }
        });
    }
 
    $(‘#cometForm‘).live(‘submit‘, function(){
        doRequest($(‘#word‘).val());
        $(‘#word‘).val(‘‘);
        return false;
    });
 
    $(document).ready(function(){
        connect();
    });
})(jQuery);
</script>
<div id="content"></div>
<div style="margin: 5px 0;">
<form action="javascript:void(0);" id="cometForm" method="get">
<input id="word" name="word" type="text" value="">
<input name="submit" type="submit" value="Send">
 
</form></div>

 

服务器端

 1 <?php
 2  
 3 $filename  = dirname(__FILE__).‘/data.txt‘;
 4  
 5 // 消息都储存在这个文件中
 6 $msg = isset($_GET[‘msg‘]) ? $_GET[‘msg‘] : ‘‘;
 7  
 8 if ($msg != ‘‘){
 9     file_put_contents($filename,$msg);
10     die();
11 }
12  
13 // 不停的循环,直到储存消息的文件被修改
14 $lastmodif    = isset($_GET[‘timestamp‘]) ? $_GET[‘timestamp‘] : 0;
15 $currentmodif = filemtime($filename);
16 while ($currentmodif <= $lastmodif){ // 如果数据文件已经被修改
17     usleep(100000); // 100ms暂停 缓解CPU压力
18     clearstatcache(); //清除缓存信息
19     $currentmodif = filemtime($filename);
20 }
21  
22 // 返回json数组
23 $response = array();
24 $response[‘msg‘]       = file_get_contents($filename);
25 $response[‘timestamp‘] = $currentmodif;
26 echo json_encode($response);
27 flush();
28  
29 ?>

 

 

方法2. websocket

这个是一个高端的js HTML库或者叫类, 可以和服务器建立长连接, 服务器可以发送socket信息,js获取信息后,读出并展示。

 

使用PHP+ajax打造聊天室应用

标签:style   blog   http   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/sailrancho/p/4147994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!