PHP實現最簡單的聊天室應用

2015-07-03    分類:WEB開發、程式設計開發、首頁精華3人評論發表於2015-07-03
核心邏輯
在定義應用程式的核心功能之前,先來看一看聊天應用程式的基本外觀,如以下截圖所示:

通過聊天視窗底部的輸入框輸入聊天文字。點選Send按鈕,就開始執行函式set_chat_msg。這是一個基於Ajax的函式,因此無需重新整理頁面就可以將聊天文字傳送到伺服器。程式在伺服器中執行chat_send_ajax.php以及使用者名稱和聊天文字。
//
// Set Chat Message
//

function set_chat_msg()
{
    if(typeof XMLHttpRequest != "undefined")
    {
        oxmlHttpSend = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
       oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
    }
    if(oxmlHttpSend == null)
    {
       alert("Browser does not support XML Http Request");
       return;
    }

    var url = "chat_send_ajax.php";
    var strname="noname";
    var strmsg="";
    if (document.getElementById("txtname") != null)
    {
        strname = document.getElementById("txtname").value;
        document.getElementById("txtname").readOnly=true;
    }
    if (document.getElementById("txtmsg") != null)
    {
        strmsg = document.getElementById("txtmsg").value;
        document.getElementById("txtmsg").value = "";
    }

    url += "?name=" + strname + "&msg=" + strmsg;
    oxmlHttpSend.open("GET",url,true);
    oxmlHttpSend.send(null);
}
PHP模組從Query String(查詢字串)中接收表單資料,更新到命名為chat的資料庫表中。chat資料庫表有命名為ID、USERNAME、CHATDATE和MSG的列。ID欄位是自動遞增欄位,所以這個ID欄位的賦值將自動遞增。當前的日期和時間,會更新到CHATDATE列。
require_once('dbconnect.php');

db_connect();

$msg = $_GET["msg"];
$dt = date("Y-m-d H:i:s");
$user = $_GET["name"];

$sql="INSERT INTO chat(USERNAME,CHATDATE,MSG) " .
      "values(" . quote($user) . "," . 
      quote($dt) . "," . quote($msg) . ");";

      echo $sql;

$result = mysql_query($sql);
if(!$result)
{
    throw new Exception('Query failed: ' . mysql_error());
    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函式。
//
// General Ajax Call
//

var oxmlHttp;
var oxmlHttpSend;

function get_chat_msg()
{
    if(typeof XMLHttpRequest != "undefined")
    {
        oxmlHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
       oxmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    if(oxmlHttp == null)
    {
        alert("Browser does not support XML Http Request");
       return;
    }

    oxmlHttp.onreadystatechange = get_chat_msg_result;
    oxmlHttp.open("GET","chat_recv_ajax.php",true);
    oxmlHttp.send(null);
}
在chat_recv_ajax.php程式中,來自於使用者的聊天訊息會通過SQL select命令進行收集。為了限制行數,在SQL查詢中還給出了限制子句(limit 200),即要求聊天資料庫表中的最後200行。所獲得的訊息再返回給Ajax函式,用於在聊天視窗中顯示內容。
require_once('dbconnect.php');

db_connect();

$sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r') 
as cdt from chat order by ID desc limit 200";
$sql = "SELECT * FROM (" . $sql . ") as ch order by ID";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());

// Update Row Information
$msg="";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
   $msg = $msg . "" .
        "" .
        "";
}
$msg=$msg . "<table style="color: blue; font-family: verdana, arial; " . 
  "font-size: 10pt;" border="0">
  <tbody><tr><td>" . $line["cdt"] . 
  " </td><td>" . $line["username"] . 
  ": </td><td>" . $line["msg"] . 
  "</td></tr></tbody></table>";

echo $msg;
資料準備就緒的同時,JavaScript函式會收集來自於PHP接收到的資料。這些資料將被安排置於DIV標籤內。oxmlHttp.responseText會保留從PHP程式接收到的聊天訊息,並複製到DIV標籤的document.getElementById(“DIV_CHAT”).innerHTML屬性。
function get_chat_msg_result(t)
{
    if(oxmlHttp.readyState==4 || oxmlHttp.readyState=="complete")
    {
        if (document.getElementById("DIV_CHAT") != null)
        {
            document.getElementById("DIV_CHAT").innerHTML =  oxmlHttp.responseText;
            oxmlHttp = null;
        }
        var scrollDiv = document.getElementById("DIV_CHAT");
        scrollDiv.scrollTop = scrollDiv.scrollHeight;
    }
}
下面的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)的許可。
評論(1)

相關文章