日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

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

發布時間:2025/4/5 php 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用PHP+ajax打造聊天室应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

方法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獲取信息后,讀出并展示。

?

轉載于:https://www.cnblogs.com/sailrancho/p/4147994.html

總結

以上是生活随笔為你收集整理的使用PHP+ajax打造聊天室应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。