服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|

服务器之家 - 编程语言 - PHP教程 - php实现简易聊天室应用代码

php实现简易聊天室应用代码

2020-11-20 11:22PHP教程网 PHP教程

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

核心逻辑

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

php实现简易聊天室应用代码

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// 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列。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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函数。

 

?
1
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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//
// 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函数,用于在聊天窗口中显示内容。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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聊天应用程序,创建该应用程序的逻辑也非常简单,即使是初学者理解起来也不会有任何困难,希望这篇文章对大家的学习有所帮助。

延伸 · 阅读

精彩推荐