基于PHP的查询使用服务器发送事件进行实时聊天.(多对一系统不进行群聊)

cod*_*eaK 6 javascript php jquery livechat server-sent-events

我正在尝试使用html服务器发送事件在网站上构建实时聊天查询表单.
我按照本教程作为基础

以下是我打算根据本教程做的事情

在客户端,要求用户输入用户名.这用作唯一聊天记录识别的主键.

客户端和服务器通过监听以下php页面来侦听服务器发送的事件.

当客户端按下发送按钮时,会将聊天发送到此php页面,该页面将其插入数据库并输出UserName

客户: var serverSource = new EventSource('ServerListener.php');

服务器: var clientSource= new EventSource('ClientListener.php');

  1. 这里有两个php文件,一个用于从客户端插入数据库聊天,另一个用于插入来自服务器的回复

  2. 当用户发送给chattoserver.php它时,这两个文件还有另一个功能,它还通知服务器收到的新聊天以及用户名搜索未读行并获取它并同时转发到聊天窗口,当服务器回复时,它发送到chatreplyreceived.php它写入数据库并通知在多个客户端监听此文件的情况下.使用用户名读取消息正确的客户端可以搜索数据库以进行回复并附加到聊天记录.

这里的日期在两个列表器页面中都正确显示,但是没有显示消息.文本文件包含发送的消息.当使用firefox网络分析工具检查数据包时.它包含响应部分中的刷新消息.但是列表器未能检测到它.我错误的是消息没有得到回应是什么?

ServerChatpage

ClientChatpage

ClientTest.php

    <html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type=text]').bind("enterKey",function(e){
//alert("Enter");
});

$('input[type=text]').keyup(function(e){
if(e.keyCode == 13)
{
  $(this).trigger("enterKey");
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementsByTagName("h1").innerHTML = xmlhttp.responseText;
                    //alert("hello");
            }

        }
        $('div.chat-box-content').append('<div class="clear"></div><span class="right">'+$(this).val()+ '</span>');
        xmlhttp.open("GET", "ClientListener.php?Message='"+$(this).val()+"'" , true);

       xmlhttp.send();
      //  xmlhttp.open("POST","ClientListener.php",true);
        //  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        //  xmlhttp.send("Message='"+$(this).val()+"'");


}
});



}

);

if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("ServerListner.php");
    source.onmessage = function(event) {
    //alert("Data Received");
    //alert(event.data);
    //alert(document.getElementsByClassName("chat-box-content").innerHTML);
      //  document.getElementsByClassName("chat-box-content").innerHTML +='<div class="clear"></div><span class="left">'+event.data+ '</span>  <br>';
      //if(event.data !==''){
        $('div.chat-box-content').append('<div class="clear"></div><span class="left">'+event.data+ '</span>');
        //}
    };
} else {
    document.getElementById("chat-box-content").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<style type="text/css">
body {
    height:3000px
}
.chat-box {
    font:normal normal 11px/1.4 Tahoma, Verdana, Sans-Serif;
    color:#333;
    width:200px;
    /* Chatbox width */
    border:1px solid #344150;
    border-bottom:none;
    background-color:white;
    position:fixed;
    right:10px;
    bottom:0;
    z-index:9999;
    -webkit-box-shadow:1px 1px 5px rgba(0, 0, 0, .2);
    -moz-box-shadow:1px 1px 5px rgba(0, 0, 0, .2);
    box-shadow:1px 1px 5px rgba(0, 0, 0, .2);
}
.chat-box > input[type="checkbox"] {
    display:block;
    margin:0 0;
    padding:0 0;
    position:absolute;
    top:0;
    right:0;
    left:0;
    width:100%;
    height:26px;
    z-index:4;
    cursor:pointer;
    opacity:0;
    filter:alpha(opacity=0);
}
.chat-box > label {
    display:block;
    height:24px;
    line-height:24px;
    background-color:#344150;
    color:white;
    font-weight:bold;
    padding:0 1em 1px;
}
.chat-box > label:before {
    content:attr(data-collapsed)
}
.chat-box .chat-box-content {
    padding:10px;
    display:none;
}
/* hover state */
 .chat-box > input[type="checkbox"]:hover + label {
    background-color:#404D5A
}
/* checked state */
 .chat-box > input[type="checkbox"]:checked + label {
    background-color:#212A35
}
.chat-box > input[type="checkbox"]:checked + label:before {
    content:attr(data-expanded)
}
.chat-box > input[type="checkbox"]:checked ~ .chat-box-content {
    display:block
}

   span
            {
                display: inline-block;
                max-width: 200px;
                background-color: white;
                padding: 5px;
                border-radius: 4px;
                position: relative;
                border-width: 1px;
                border-style: solid;
                border-color: grey;
            }

            left
            {
                float: left;
            }

            span.left:after
            {
                content: "";
                display: inline-block;
                position: absolute;
                left: -8.5px;
                top: 7px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-right: 8px solid white;
            }

            span.left:before
            {
                content: "";
                display: inline-block;
                position: absolute;
                left: -9px;
                top: 7px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-right: 8px solid black;
            }

            span.right:after
            {
                content: "";
                display: inline-block;
                position: absolute;
                right: -8px;
                top: 6px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-left: 8px solid #dbedfe;
            }

            span.right:before
            {
                content: "";
                display: inline-block;
                position: absolute;
                right: -9px;
                top: 6px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-left: 8px solid black;
            }

            span.right
            {
                float: right;
                background-color: #dbedfe;
            }

            .clear
            {
                clear: both;
            }

            input[type="text"]{
    width:96%;
    margin:1%;

}/*INSERT INTO `users`( `userRole`, `userName`, `createdOn`, `emailId`, `is_active`, `password`) VALUES (1,'admin_chat',NOW(),'sdmd@sdmd.com',1,'123456') ON DUPLICATE KEY */

</style>
</head>
<body>
<div class="chat-box">
    <input type="checkbox" />
    <label data-expanded="Close Chatbox" data-collapsed="Open Chatbox"></label>
    <div class="chat-box-content">
<span class="left">messmessage</span>
<div class="clear"></div>
<span class="right">messagemessagemessage</span>
<div class="clear"></div>
<span class="left">messagemessagsage</span>
<div class="clear"></div>
<span class="right">messagemessagemessage</span>
    </div>
     <input type="text" />
</div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

ClientListener.php

<?php

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//header("refresh: 5;");

   if (ISSET($_GET['Message'])) {

$msg =$_GET['Message'];
if(!empty($msg)){
 $fp = fopen("_chat.txt", 'a');  
    fwrite($fp,$msg."\n\n");  
    fclose($fp);  
}

echo "data: $msg\n\n";


flush();


}
?>
Run Code Online (Sandbox Code Playgroud)

ServerTestPage.php

    <html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type=text]').bind("enterKey",function(e){
//alert("Enter");
});

$('input[type=text]').keyup(function(e){
if(e.keyCode == 13)
{
  $(this).trigger("enterKey");

          var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementsByTagName("h1").innerHTML = xmlhttp.responseText;
                    //alert("hello");
            }

        }
        $('div.chat-box-content').append('<div class="clear"></div><span class="right">'+$(this).val()+ '</span>');
       xmlhttp.open("GET", "ServerListner.php?Message='"+$(this).val()+"'" , true);
       xmlhttp.send();
        //  xmlhttp.open("POST","ServerListner.php",true);
        ///  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        //  xmlhttp.send("Message='"+$(this).val()+"'");

}
});



}

);

if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("ClientListener.php");
    source.onmessage = function(event) {
    //alert("Data Received");
    alert(event.data);
    //alert(document.getElementsByClassName("chat-box-content").innerHTML);
      //  document.getElementsByClassName("chat-box-content").innerHTML +='<div class="clear"></div><span class="left">'+event.data+ '</span>  <br>';
     // if(event.data!==''){
        console.log(event.data);
        $('div.chat-box-content').append('<div class="clear"></div><span class="left">'+event.data+ '</span>');

    //  }
    };
} else {
    document.getElementById("chat-box-content").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<style type="text/css">
body {
    height:3000px
}
.chat-box {
    font:normal normal 11px/1.4 Tahoma, Verdana, Sans-Serif;
    color:#333;
    width:200px;
    /* Chatbox width */
    border:1px solid #344150;
    border-bottom:none;
    background-color:white;
    position:fixed;
    right:10px;
    bottom:0;
    z-index:9999;
    -webkit-box-shadow:1px 1px 5px rgba(0, 0, 0, .2);
    -moz-box-shadow:1px 1px 5px rgba(0, 0, 0, .2);
    box-shadow:1px 1px 5px rgba(0, 0, 0, .2);
}
.chat-box > input[type="checkbox"] {
    display:block;
    margin:0 0;
    padding:0 0;
    position:absolute;
    top:0;
    right:0;
    left:0;
    width:100%;
    height:26px;
    z-index:4;
    cursor:pointer;
    opacity:0;
    filter:alpha(opacity=0);
}
.chat-box > label {
    display:block;
    height:24px;
    line-height:24px;
    background-color:#344150;
    color:white;
    font-weight:bold;
    padding:0 1em 1px;
}
.chat-box > label:before {
    content:attr(data-collapsed)
}
.chat-box .chat-box-content {
    padding:10px;
    display:none;
}
/* hover state */
 .chat-box > input[type="checkbox"]:hover + label {
    background-color:#404D5A
}
/* checked state */
 .chat-box > input[type="checkbox"]:checked + label {
    background-color:#212A35
}
.chat-box > input[type="checkbox"]:checked + label:before {
    content:attr(data-expanded)
}
.chat-box > input[type="checkbox"]:checked ~ .chat-box-content {
    display:block
}

   span
            {
                display: inline-block;
                max-width: 200px;
                background-color: white;
                padding: 5px;
                border-radius: 4px;
                position: relative;
                border-width: 1px;
                border-style: solid;
                border-color: grey;
            }

            left
            {
                float: left;
            }

            span.left:after
            {
                content: "";
                display: inline-block;
                position: absolute;
                left: -8.5px;
                top: 7px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-right: 8px solid white;
            }

            span.left:before
            {
                content: "";
                display: inline-block;
                position: absolute;
                left: -9px;
                top: 7px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-right: 8px solid black;
            }

            span.right:after
            {
                content: "";
                display: inline-block;
                position: absolute;
                right: -8px;
                top: 6px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-left: 8px solid #dbedfe;
            }

            span.right:before
            {
                content: "";
                display: inline-block;
                position: absolute;
                right: -9px;
                top: 6px;
                height: 0px;
                width: 0px;
                border-top: 8px solid transparent;
                border-bottom: 8px solid transparent;
                border-left: 8px solid black;
            }

            span.right
            {
                float: right;
                background-color: #dbedfe;
            }

            .clear
            {
                clear: both;
            }

            input[type="text"]{
    width:96%;
    margin:1%;

}/*INSERT INTO `users`( `userRole`, `userName`, `createdOn`, `emailId`, `is_active`, `password`) VALUES (1,'admin_chat',NOW(),'sdmd@sdmd.com',1,'123456') ON DUPLICATE KEY */

</style>
</head>
<body>
<div class="chat-box">
    <input type="checkbox" />
    <label data-expanded="Close Chatbox" data-collapsed="Open Chatbox"></label>
    <div class="chat-box-content">
<span class="left">messmessage</span>
<div class="clear"></div>
<span class="right">messagemessagemessage</span>
<div class="clear"></div>
<span class="left">messagemessagsage</span>
<div class="clear"></div>
<span class="right">messagemessagemessage</span>
    </div>
     <input type="text" />
</div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

ServerListener

    <?php
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        //header("refresh: 3;");

            if (ISSET($_GET['Message'])) {


    $msg =$_GET['Message'];
    if(!empty($msg)){
     $fp = fopen("_chat.txt", 'a');  
        fwrite($fp,$msg."\n\n");  
        fclose($fp);  
    }


    echo "data: $msg\n\n";

    flush();

}



        ?>
Run Code Online (Sandbox Code Playgroud)

Bar*_*n01 0

如果您现在想要基于您的方法的信息,那么这是错误的,您应该查看WebSockets API教程

然而,在这两种情况下,对于服务器系统来说,php 都是错误的语言,您必须让客户端轮询以获取新信息,其次这不是真正的客户端服务器关系

在客户端,用户被要求提供用户名。这用作唯一聊天日志标识的主键。

这是不正确的,主键永远不应该相同,因此如果您使用数据库,则用户名不能成为主键,大多数人在数据库中使用 AUTO_INCRMENT 键作为主键。

如果您使用 jQuery 为什么您使用本机 XMLHttpRequest 客户端而不是jQuery 的 XHR

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementsByTagName("h1").innerHTML = xmlhttp.responseText;
            //alert("hello");
    }
}
$('div.chat-box-content').append('<div class="clear"></div><span class="right">'+$(this).val()+ '</span>');
xmlhttp.open("GET", "ClientListener.php?Message='"+$(this).val()+"'" , true);
xmlhttp.send();
Run Code Online (Sandbox Code Playgroud)

在做如此复杂的事情之前,请先进行研究,以确保您能够使用所需的语言。如果您还没有达到可以阅读本机 JavaScript 教程并了解如何将其转换为 JavaScript 框架的程度,那么您还没有准备好使用它。