PHP Classes
PHP Classes
elePHPant
Icontem

Fast PHP Comet Chat System Tutorial

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog Fast PHP Comet Chat S...   Post a comment Post a comment   See comments See comments (3)   Trackbacks (0)  

Author:

Posted on:

Categories: PHP Tutorials

Comet is a form of communicating with a Web server using HTTP requests that do not finish returning a response, so they can continue to communicate to the Web browser.

Read this article to learn how to use the Comet approach to implement a simple Web chat system.




Contents

Introduction

Existing Approaches

Implementations of Comet Servers

Building a simple chat in PHP

Conclusion


Introduction

Comet relies on regular HTTP requests to keep sending updated information to the browser without delay. This diagram shows a way for a browser and a HTTP server to communicate to process Comet requests.

comet_diagram_1

Interaction with a server using Comet is processed as follows.

  1. The browser opens the page of the site.
  2. After the page is loaded, JavaScript establishes a persistent connection to the comet server.
  3. While the page is opened, your server can send any messages to the browser. To do this, it uses an API to the send messages to the Comet server.
  4. The Comet server uses an already opened connection with the browser and delivers the received message to it.
  5. The JavaScript API receives the message from the server invokes your callback.

Existing Approaches

There are quite a few approaches to implement, but currently the most typical is to use WebSockets, rather than using others such as Polling, Long polling, «endless» iframe and Flash sockets, because WebSockets are already supported by all modern browsers.

Implementations of Comet servers

Here are a few implementations of Comet servers. It would be good if anybody shares about similar projects.

NameLicenseLicense
CentrifugeMITPython, Ruby, Java, PHP
dklab_realplexorGPLPHP
Nginx Push Stream ModuleGPLREST API
APE ProjectGPLREST API
comet-server.ruAs a service, with the installation of your server. Delphi, C, C++, Eifel, Java, Lisp, Perl,
PHP, Python, Ruby, Smalltalk, Node.js,
Bash, Component Pascal and Tcl
(All languages for which there is MySQL client)
fanout.ioAs a service, with the installation of your server Python, Ruby, PHP, Node, Go, Django
pusher.comAs a serviceREST API and library for Ruby, PHP, .NET,
Node.js, Python
hydna.com As a serviceC++, Erlang, Go (Push only), Java, JavaScript,
Julia (Push only), Lua (Push only), .NET, Node.js,
Objective-C, PHP (Push only), Python (Push only),
Ruby (Push only)
tambur.ioAs a serviceRuby, Python, PHP, Java, Erlang

There is a summary table of Comet server implementations, but it dates back to the year 2009 already.

Building a Simple Chat system in PHP

Let us examine the example of the construction of chat system. We shall use comet-server.ru as our Comet server.

The chat system will work as follows:

  • The user visits a page and immediately signs in to a JavaScript API to get instant messages from a chat channel.
  • To send a message, an AJAX request is used to send a text message to the server running PHP.
  • PHP processes the received message and saves it to a database to do whatever you want.
  • Then PHP is connected to the Comet server and passes it a CometQL request to send messages to the channel.
  • The Comet server receives from PHP the message and sends to everyone that is subscribed to the channel.

Here is the code for receiving messages from the chat system:

<!DOCTYPE HTML>
<html>
<head>
<!-- Connecting libraries -->
<script src="//comet-server.ru/CometServerApi.js"></script>
<script src="//comet-server.ru/doc/CometQL/simplePhpChat/jquery.min.js">
</script>
</head>
<body>

<!-- The unit in which we add the received message -->
<div
   id="textHolder"
   style="margin-top:10px;border:1px solid #000;padding:10px;"
></div>
<hr>
<input type="text" id="msgText" placeholder="Message text">
<input type="button" value="Send"  onclick="sendMsg();">

To communicate with the comet server used
<a href="http://comet-server.ru/wiki/doku.php/comet:cometql">CometQL</a>.
CometQL - api is to work with the comets, the MySQL server protocol.
<script type="text/javascript">
$(document).ready(function(){

    /** 
     * Sign up to receive messages from the channel SimplePhpChat.
     */
    CometServer().subscription("SimplePhpChat", function(event){
        console.log(
            "We received a message from the channel SimplePhpChat.",
            event.data,
            event
        );
        $("#textHolder").html( $("#textHolder").html() +"<hr>"+event.data);
    })

    /** 
     * Connecting to a server comets. To be able to receive commands.
     * dev_id your public identity of the developer.
     */
    CometServer().start({dev_id:15 })
})

function sendMsg(){

	var text = $("#msgText").val();
	
    jQuery.ajax({
        url: "//comet-server.ru/doc/CometQL/simplePhpChat/sendMsgToChat.php",
        type: "GET",
        data:"text="+encodeURIComponent(text),
        success: function(){
            $("#msgText").val('');
        }
    });
}
</script>
</body>
</html>

Here is the code for sending messages from PHP:

// Connecting to the comet server with a login and password to access the demo 
// (get your data connection as possible after registration comet-server.ru)
// Login 15
// Password lPXBFPqNg3f661JcegBY0N0dPXqUBdHXqj2cHf04PZgLHxT6z55e20ozojvMRvB8
// Base data CometQL_v1
$link = mysqli_connect(
            "app.comet-server.ru", "15", 
            "lPXBFPqNg3f661JcegBY0N0dPXqUBdHXqj2cHf04PZgLHxT6z55e20ozojvMRvB8",
            "CometQL_v1"
        );

// send a message to the channel
mysqli_query(
    $link,
    "INSERT INTO
        pipes_messages
        (name, event, message)
    VALUES
        ('SimplePhpChat',
         '',
         '".mysqli_real_escape_string($link,htmlspecialchars($_GET['text']))."'
        );"
);

Conclusion

This is a very simple way to implement a simple chat server based on the Comet. Personally, I really like this approach.

If you like this article please share it with your colleague developers. Just post a comment below if you have questions.




You need to be a registered user or login to post a comment

1,507,076 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:

FacebookGmail
HotmailStackOverflow
GitHubYahoo


Comments:

2. Thanks for sharing, I agree with you! - mayduavongts (2018-03-31 14:34)
Thanks for sharing, I agree with you!... - 0 replies
Read the whole comment and replies

1. Practical usage under high load - Oleg Zorin (2017-06-12 19:44)
It's very good idea and it's worth of using... - 1 reply
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog Fast PHP Comet Chat S...   Post a comment Post a comment   See comments See comments (3)   Trackbacks (0)