PHP 대화방 애플리케이션 구현 방법 아이디어

伊谢尔伦
풀어 주다: 2023-03-02 21:10:01
원래의
2164명이 탐색했습니다.

소개

채팅 앱은 온라인에서 매우 일반적입니다. 개발자에게는 이러한 애플리케이션을 구축할 때 다양한 옵션이 있습니다. 이 문서에서는 페이지를 새로 고치지 않고도 메시지를 보내고 받을 수 있는 PHP-AJAX 기반 채팅 애플리케이션을 구현하는 방법을 설명합니다.

핵심 로직

애플리케이션의 핵심 기능을 정의하기 전에 다음 스크린샷과 같이 채팅 애플리케이션의 기본 모습을 살펴보겠습니다.

PHP 대화방 애플리케이션 구현 방법 아이디어

채팅창 하단의 입력창을 통해 채팅 내용을 입력하세요. 보내기 버튼을 클릭하면 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 모듈은 쿼리 문자열(쿼리 문자열)로부터 양식 데이터를 수신하여 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();
}
로그인 후 복사

데이터베이스 테이블의 모든 사용자로부터 채팅 메시지를 받기 위해 타이머 함수를 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 쿼리에 제한 절(한도 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 채팅 애플리케이션으로 개선될 수 있습니다. 이 애플리케이션을 생성하는 논리도 매우 간단합니다. 초보자라도 이해하는데 어려움은 없을 것입니다.


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!