PHP头条
热点:

PHP实现最简单的聊天室应用


介绍

聊天应用程序在网上非常常见。开发人员在构建这类应用程序时的选择也很多。这篇文章介绍了如何实现基于PHP-AJAX的聊天应用程序,并且不需要刷新页面就可以发送和接收消息。

核心逻辑

在定义应用程序的核心功能之前,先来看一看聊天应用程序的基本外观,如以下截图所示:

通过聊天窗口底部的输入框输入聊天文本。点击Send按钮,就开始执行函数set_chat_msg。这是一个基于Ajax的函数,因此无需刷新页面就可以将聊天文本发送到服务器。程序在服务器中执行chat_send_ajax.php以及用户名和聊天文本。

  1. // 
  2. // Set Chat Message 
  3. // 
  4.  
  5. function set_chat_msg() 
  6.     if(typeof XMLHttpRequest != "undefined"
  7.     { 
  8.         oxmlHttpSend = new XMLHttpRequest(); 
  9.     } 
  10.     else if (window.ActiveXObject) 
  11.     { 
  12.        oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp"); 
  13.     } 
  14.     if(oxmlHttpSend == null
  15.     { 
  16.        alert("Browser does not support XML Http Request"); 
  17.        return
  18.     } 
  19.  
  20.     var url = "chat_send_ajax.php"
  21.     var strname="noname"
  22.     var strmsg=""
  23.     if (document.getElementById("txtname") != null
  24.     { 
  25.         strname = document.getElementById("txtname").value; 
  26.         document.getElementById("txtname").readOnly=true
  27.     } 
  28.     if (document.getElementById("txtmsg") != null
  29.     { 
  30.         strmsg = document.getElementById("txtmsg").value; 
  31.         document.getElementById("txtmsg").value = ""
  32.     } 
  33.  
  34.     url += "?name=" + strname + "&msg=" + strmsg; 
  35.     oxmlHttpSend.open("GET",url,true); 
  36.     oxmlHttpSend.send(null); 

PHP模块从Query String查询字符串)中接收表单数据,更新到命名为chat的数据库表中。chat数据库表有命名为IDUSERNAMECHATDATEMSG的列。ID字段是自动递增字段,所以这个ID字段的赋值将自动递增。当前的日期和时间,会更新到CHATDATE列。

  1. require_once('dbconnect.php'); 
  2.  
  3. db_connect(); 
  4.  
  5. $msg = $_GET["msg"]; 
  6. $dt = date("Y-m-d H:i:s"); 
  7. $user = $_GET["name"]; 
  8.  
  9. $sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " . 
  10.       "values(" . quote($user) . "," . 
  11.       quote($dt) . "," . quote($msg) . ");"
  12.  
  13.       echo $sql; 
  14.  
  15. $result = mysql_query($sql); 
  16. if(!$result) 
  17.     throw new Exception('Query failed: ' . mysql_error()); 
  18.     exit(); 

为了接收来自数据库表中所有用户的聊天消息,timer函数被设置为循环5秒调用以下的JavaScript命令,即每隔5秒时间执行get_chat_msg函数。

var t = setInterval(function(){get_chat_msg()},5000);

get_chat_msg是一个基于Ajax的函数。它执行chat_recv_ajax.php程序以获得来自于数据库表的聊天信息。在 onreadystatechange属性中,另一个JavaScript 函数get_chat_msg_result被连接起来。在返回来自于数据库表中的聊天消息的同时,程序控制进入到 get_chat_msg_result函数。

  1. // 
  2. // General Ajax Call 
  3. // 
  4.  
  5. var oxmlHttp; 
  6. var oxmlHttpSend; 
  7.  
  8. function get_chat_msg() 
  9.     if(typeof XMLHttpRequest != "undefined"
  10.     { 
  11.         oxmlHttp = new XMLHttpRequest(); 
  12.     } 
  13.     else if (window.ActiveXObject) 
  14.     { 
  15.        oxmlHttp = new ActiveXObject("Microsoft.XMLHttp"); 
  16.     } 
  17.     if(oxmlHttp == null
  18.     { 
  19.         alert("Browser does not support XML Http Request"); 
  20.        return
  21.     } 
  22.  
  23.     oxmlHttp.onreadystatechange = get_chat_msg_result; 
  24.     oxmlHttp.open("GET","chat_recv_ajax.php",true); 
  25.     oxmlHttp.send(null); 

在chat_recv_ajax.php程序中,来自于用户的聊天消息会通过SQL select命令进行收集。为了限制行数,在SQL查询中还给出了限制子句limit 200),即要求聊天数据库表中的最后200行。所获得的消息再返回给Ajax函数,用于在聊天窗口中显示内容。

  1. require_once('dbconnect.php'); 
  2.  
  3. db_connect(); 
  4.  
  5. $sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r'
  6. as cdt from chat order by ID desc limit 200"; 
  7. $sql = "SELECT * FROM (" . $sql . ") as ch order by ID"
  8. $result = mysql_query($sql) or die('Query failed: ' . mysql_error()); 
  9.  
  10. // Update Row Information 
  11. $msg=""
  12. while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) 
  13.    $msg = $msg . "" . 
  14.         "" . 
  15.         ""
  16. $msg=$msg . "<table style="color: blue; font-family: verdana, arial; " . 
  17.   "font-size: 10pt;" border="0"
  18.   <tbody><tr><td>" . $line["cdt"] . 
  19.   " </td><td>" . $line["username"] . 
  20.   ": </td><td>" . $line["msg"] . 
  21.   "</td></tr></tbody></table>"
  22.  
  23. echo $msg; 
  24.  
  25. 数据准备就绪的同时,JavaScript函数会收集来自于PHP接收到的数据。这些数据将被安排置于DIV标签内。oxmlHttp.responseText会保留从PHP程序接收到的聊天消息,并复制到DIV标签的document.getElementById(“DIV_CHAT”).innerHTML属性。 
  26.  
  27. function get_chat_msg_result(t) 
  28.     if(oxmlHttp.readyState==4 || oxmlHttp.readyState=="complete"
  29.     { 
  30.         if (document.getElementById("DIV_CHAT") != null
  31.         { 
  32.             document.getElementById("DIV_CHAT").innerHTML =  oxmlHttp.responseText; 
  33.             oxmlHttp = null
  34.         } 
  35.         var scrollDiv = document.getElementById("DIV_CHAT"); 
  36.         scrollDiv.scrollTop = scrollDiv.scrollHeight; 
  37.     } 

下面的SQL CREATE TABLE命令可用于创建名为chat的数据库表。所有由用户输入的信息都会进入到数据库表中。

create table chat( id bigint AUTO_INCREMENT,username varchar(20),
chatdate datetime,msg varchar(500), primary key(id));

兴趣点

这段用于实现聊天应用程序的代码非常有意思。它可以改进成为一个完全成熟的HTTP聊天应用程序。创建该应用程序的逻辑也非常简单。即使是初学者理解起来也不会有任何困难。

许可证

这篇文章,以及任何相关的源代码和文件,都获得了The Code Project Open License (CPOL)的许可。

译文链接:http://www.codeceo.com/article/php-chart-app.html
英文原文:Chat Application in PHP



www.phpzy.comtrue/php/21706.htmlTechArticlePHP实现最简单的聊天室应用 介绍 聊天应用程序在网上非常常见。开发人员在构建这类应用程序时的选择也很多。这篇文章介绍了如何实现基于PHP-AJAX的聊天应用程序,并且不需要刷新页...

相关文章

PHP之友评论

今天推荐