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

后端开发   发布日期:2025年05月05日   浏览次数:206

方法1.  comet

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

浏览器端

  1. <meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
  2. <title>Comet Test</title>
  3. <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
  4. <script type="text/javascript">
  5. (function($){
  6. function handleResponse(response){
  7. $('#content').append('<div>' + response['msg'] + '</div>');
  8. }
  9. var timestamp = 0;
  10. var url = './chat_backend.php';
  11. var noerror = true;
  12. var ajax;
  13. function connect() {
  14. ajax = $.ajax(url, {
  15. type: 'get',
  16. data: { 'timestamp' : timestamp },
  17. success: function(transport) {
  18. eval('var response = '+transport);
  19. timestamp = response['timestamp'];
  20. handleResponse(response);
  21. noerror = true;
  22. },
  23. complete: function(transport) {
  24. (!noerror) && setTimeout(function(){ connect() }, 5000) || connect();
  25. noerror = false;
  26. }
  27. });
  28. }
  29. function doRequest(request) {
  30. $.ajax(url, {
  31. type: 'get',
  32. data: { 'msg' : request }
  33. });
  34. }
  35. $('#cometForm').live('submit', function(){
  36. doRequest($('#word').val());
  37. $('#word').val('');
  38. return false;
  39. });
  40. $(document).ready(function(){
  41. connect();
  42. });
  43. })(jQuery);
  44. </script>
  45. <div ></div>
  46. <div style="margin: 5px 0;">
  47. <form action="javascript:void(0);" >
  48. <input >
  49. <input name="submit" type="submit" value="Send">
  50. </form></div>

 

服务器端

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

 

 

方法2. websocket

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

 

以上就是使用PHP+ajax打造聊天室应用的详细内容,更多关于使用PHP+ajax打造聊天室应用的资料请关注九品源码其它相关文章!