Javascript 基于Php的查询实时聊天,使用服务器发送的事件。(多对一系统而非群聊)

Javascript 基于Php的查询实时聊天,使用服务器发送的事件。(多对一系统而非群聊),javascript,php,jquery,server-sent-events,livechat,Javascript,Php,Jquery,Server Sent Events,Livechat,我正在尝试使用html服务器发送的事件在网站中构建实时聊天查询表单。 以下是基于本教程我打算做的事情 在客户端,要求用户输入用户名。该用户名用作唯一聊天日志标识的主密钥 客户端和服务器通过侦听以下php页面来侦听服务器发送的事件 当客户端按下发送按钮时,聊天被发送到此php页面,该页面将其插入数据库并输出用户名 客户端:var serverSource=neweventsource('ServerListener.php') 服务器:var clientSource=neweventsourc

我正在尝试使用html服务器发送的事件在网站中构建实时聊天查询表单。

以下是基于本教程我打算做的事情 在客户端,要求用户输入用户名。该用户名用作唯一聊天日志标识的主密钥

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

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

客户端:
var serverSource=neweventsource('ServerListener.php')

服务器:
var clientSource=neweventsource('ClientListener.php')

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

  • 当用户发送到
    chattoserver.php
    时,这两个文件还有另一个功能,它还通知服务器收到的新聊天以及用户名,搜索未读的行并获取它,并显示到聊天窗口 同样,当服务器回复时,它会被发送到
    chatpreplyreceived.php
    ,在那里它会写入数据库并通知客户端。因此,如果有多个客户端正在侦听此文件。读取消息时,使用用户名更正客户端可以搜索数据库中的回复并将其附加到聊天日志中

  • 在这里,日期在两个listner页面中都正确显示,但消息没有显示。文本文件包含已发送的消息。使用firefox网络分析工具检查数据包时,它在响应部分包含已清除的消息。但是listner未能检测到它。我做错了什么,消息没有被发送回声

    ClientTest.php
    
    $(文档).ready(函数(){
    $('input[type=text]')。绑定(“enterKey”,函数(e){
    //警报(“输入”);
    });
    $('input[type=text]')。键控(函数(e){
    如果(e.keyCode==13)
    {
    $(此).trigger(“enterKey”);
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=函数(){
    if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementsByTagName(“h1”).innerHTML=xmlhttp.responseText;
    //警惕(“你好”);
    }
    }
    $('div.chat-box-content').append('+$(this.val()+'');
    open(“GET”,“ClientListener.php?Message='”+$(this.val()+”,true);
    xmlhttp.send();
    //open(“POST”,“ClientListener.php”,true);
    //setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
    //send(“Message=”+$(this.val()+”);
    }
    });
    }
    );
    if(typeof(EventSource)!=“未定义”){
    var source=neweventsource(“ServerListner.php”);
    source.onmessage=函数(事件){
    //警报(“收到的数据”);
    //警报(事件数据);
    //警报(document.getElementsByClassName(“聊天盒内容”).innerHTML);
    //document.getElementsByClassName(“聊天盒内容”).innerHTML+=''+事件.data+'
    '; //如果(event.data!=''){ $('div.chat-box-content').append(''+事件.数据+''); //} }; }否则{ document.getElementById(“聊天盒内容”).innerHTML=“对不起,您的浏览器不支持服务器发送的事件…”; } 身体{ 高度:3000px } .聊天室{ 字体:普通11px/1.4 Tahoma,Verdana,无衬线; 颜色:#333; 宽度:200px; /*聊天室宽度*/ 边框:1px实心#344150; 边框底部:无; 背景色:白色; 位置:固定; 右:10px; 底部:0; z指数:9999; -webkit盒阴影:1px 1px 5px rgba(0,0,0,2); -莫兹盒阴影:1px1p5pRGBA(0,0,0,2); 盒影:1px1p5pRGBA(0,0,0,2); } .chat box>输入[type=“checkbox”]{ 显示:块; 利润率:0; 填充:0; 位置:绝对位置; 排名:0; 右:0; 左:0; 宽度:100%; 高度:26px; z指数:4; 光标:指针; 不透明度:0; 过滤器:alpha(不透明度=0); } .聊天室>标签{ 显示:块; 高度:24px; 线高:24px; 背景色:#344150; 颜色:白色; 字体大小:粗体; 填充:0 1em 1px; } .聊天室>标签:之前{ 内容:attr(数据折叠) } .聊天室.聊天室内容{ 填充:10px; 显示:无; } /*悬停状态*/ .chat box>输入[type=“checkbox”]:悬停+标签{ 背景色:#404D5A } /*检查状态*/ .chat box>输入[type=“checkbox”]:选中+标签{ 背景色:#212A35 } .chat box>输入[type=“checkbox”]:选中+标签:之前{ 内容:attr(数据扩展) } .chat box>输入[type=“checkbox”]:选中~。聊天框内容{ 显示:块 } 跨度 { 显示:内联块; 最大宽度:200px; 背景色:白色; 填充物:5px; 边界半径:4px; 位置:相对位置; 边框宽度:1px; 边框样式:实心; 边框颜色:灰色; } 左边 { 浮动:左; } 左:之后 { 内容:“; 显示:内联块; 位置:绝对位置; 左:-8.5px; 顶部:7px; 高度:0px; 宽度:0px; 边框顶部:8px实心透明; 边框底部:8px实心透明; 右边框:8px纯白; } 左:之前 { 内容:“; 显示:内联块; 位置:绝对位置; 左:-9px; 顶部:7px; 高度:0px; 宽度:0px; 边框顶部:8px实心透明; 边框底部:8px实心透明;
        <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>
    
    <?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();
    
    
    }
    ?>
    
        <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();
    
    }
    
    
    
            ?>
    
    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();