javascript - 使用服务器发送事件的基于 Php 的查询实时聊天。(多对一系统不是群聊)

标签 javascript php jquery server-sent-events livechat

我正在尝试使用 html 服务器发送的事件在网站中构建实时聊天查询表单。
I am following this tutorial as base for it

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

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

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

当客户端按下发送按钮时,聊天被发送到这个 php 页面,该页面将其插入数据库并输出用户名

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

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

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

  2. 当用户发送到 chattoserver.php 时,这两个文件还有另一个功能,它还会通知服务器收到的新聊天以及用户名,它会搜索未读行并获取它并将其附加到聊天窗口 类似地,当服务器回复时,它会发送到 chatreplyreceived.php 并在其中写入数据库并通知客户端。因此,如果有多个客户端收听此文件。读取消息正确的客户端用户名可以在数据库中搜索回复并附加到聊天记录。

此处日期在两个监听器页面中均正确显示,但未显示消息。文本文件包含已发送的消息。当使用 firefox 网络分析工具检查数据包时。它在响应部分包含刷新的消息。但是监听器未能检测到它。我做错了什么消息没有被回显

ServerChatpage

ClientChatpage

客户端测试.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>

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();


}
?>

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>

服务器监听器

    <?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();

}



        ?>

最佳答案

如果你现在想要基于你的方法的信息,这是错误的,你应该查看 WebSockets API和一个 Tutorial

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

At client side User is asked for username .This is used as a primarykey for unique chat log identification .

这不可能是正确的,主键永远不应该相同,所以如果您使用数据库,用户名不能是主键,大多数人使用 AUTO_INCREMENT数据库中的键作为主键。

如果您使用 jQuery 为什么要使用 native XMLHttpRequest 客户端而不是 jQuery's 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();

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

关于javascript - 使用服务器发送事件的基于 Php 的查询实时聊天。(多对一系统不是群聊),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684625/

相关文章:

javascript - 在获取图像大小时绕过异步

php - JS 代码中出现 smarty 错误

javascript - 从代码隐藏调用 .js 文件函数

javascript - 如何将链接列表显示为下拉选择?

PHP/mysql数组查找算法

php - 在 laravel 中未发现错误

javascript - jQuery:每 X 秒运行一次 AJAX,仅持续 60 秒?

javascript - 删除 DIV 中的子节点

java - php 和 java 中需要相同的字符串比较函数

jquery - 将 word 替换为 jQuery