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

來源:互聯網
上載者:User

標籤: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打造聊天室應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.