Php Based enquiry real time chat using server sent events.(Many to one system Not group chat)
Asked Answered
B

1

6

I am trying to build a live chat enquiry form in a website using html server sent events.
I am following this tutorial as base for it

Here is what i intend to do based on this tutorial

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

The client and server listens for server sent events by listening to following php pages.

When client press send button chat is sent to this php page which inserts it into database and outputs UserName

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

Server: var clientSource= new EventSource('ClientListener.php');

  1. Here there are two php files one for inserting to database chat from client side and other for inserting for reply from server

  2. Both these files also has another function when user sends to chattoserver.php it also notify server of new chat received along with user name it search for unread rows and fetch it and appennd to chat window similarly when server replies it is send to chatreplyreceived.php where it writes database and notify the client .So in case of multiple clients listening to this file .Reading the message correct client with user name can search database for reply and appending to chat log .

Here the dates are showed correctly in both listner pages but the message is not shown .And text file contains messages sent .When checked packets using firefox network analysis tool.It contains flushed out message in response part.But the listners failing to detect it .What is that i am doing wrong that messages are not being echoed ?

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(),'[email protected]',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(),'[email protected]',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>

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

}



        ?>
Boucher answered 20/9, 2015 at 21:44 Comment(5)
Have you thought about using websockets for real-time updating?Egestion
No ? @ChrisBeckett cant we do real time updating with SSEBoucher
@SachinDivakar You can have real time updating with SSE, however if you look at the tutorial you linked in your question it takes bit time to come through. If you was to use websockets the time it takes is much quicker. Example of websockets: socketo.me/demo. Also could you display any errors from console.log if there is any to show the problem you're having?Egestion
@SachinDivakar If any questions, just ask away :)Egestion
Chris beckett what is baffling is no error is being logged.The file to which I write the chat for testing contains all chat but after that nothing happenning but the same thing when uses current date auto refreshes the page works correctly But does not work when some And I have already read HTML5rocks before and after that only I started writing code for this appBoucher
C
0

If you wanting information based on your Approach nowadays this is just wrong you should be looking at WebSockets API and a Tutorial

however php is the wrong language for a Server system in both cased you have to have the client poll for new information this is not a true client server relationship secondly

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

This can't be correct a primary key should never be the same so if you using a database a username can't be a primary key most people use an AUTO_INCREMENT key in a database for a primary key.

if your using jQuery why are you using the native XMLHttpRequest client and not 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();

Before doing something this complex do the research and more sure you able to use the languages you need. if you not at a point where you can read a tutorial in native JavaScript and understand how to translate it to a JavaScript framework you are not ready to use it.

Crozier answered 29/9, 2015 at 10:13 Comment(9)
Bro I was doing it for a small website where max simulataneous enquiry(chat) is very small .So php will suffice for now.Bro I have thinked about Db and other things It would be too complex to write that down I left all that out with a simple implementation.what I am stuck is when a chat is sent to php page it received and written to log file for debugging purpose but when output stream is flushed nothing happens even on inspecting the request response containsBoucher
yeah read the code the client is not reading the messages from anything it expect's to be given the message it wont handle anything that the specific client did not send that why i gave this answer.Crozier
So Bro just do one thing I have commented out a few lines header('refresh'); and also just echo current server time it works normally that is shown in thewebby.net16.net/TheWebby/ClientTestPage.php and thewebby.net16.net/TheWebby/ServerTestPage.phpBoucher
So it should go: Client -> send message to server -> server save message -> another client -> asks for messages -> server loads new messages and sends them back to client Client then handles displaying themCrozier
Bro its not about the implemenatation that I am worried its about the flush output not received at listner client page bro check out the links in comments.This is actually a simplified skeletal structure not the way the actual application is about to go .Bro server sent events are being used only with intention of avoiding polling and I have thought about its workBoucher
if something is not received it's not sentCrozier
Let us continue this discussion in chat.Crozier
No bro in mozilla in the response side the data is seen when you analysis request using inspect element .And the said data is being logged successfully in text file.Bro you are actually not trying to solve what I want you are suggesting the alternative things and how the system should be implementedBoucher
Move to chat and tell me what the problem is no where in your answer have you said what the problem is then if it's not that it's not workingCrozier

© 2022 - 2024 — McMap. All rights reserved.