PHP chat example

An example of using the CppComet server to create a chat.

chat demo

Scheme of chat

Typical scheme of chat:

Typical scheme of chat

  • Connecting to the comet server by websockets
  • Send ajax message for add new massage to chat
  • Send message to CppComet
  • CppComet send messages for all subscribers in pipe
  • Add message to database (optional)

Step 1. Connecting to the comet server

CppComet has cloud saas alternative that can be used for testing and demo access. In the following examples I will use demonstration access from for those who could not or were too lazy to deploy the server on their VPS

Login: 15

To connect to the comet server from the JavaScript API, use the following command:

cometApi.start({node:"", dev_id:15})

* in parameter node - set hostname of your own server * parameter dev_id - use only if you use saas service

Step 2. Send message to server

* Send ajax query to php back-end * Send CometQL query for comet server

code of php back-end

Connection code to CppComet using MySQL protocol:

$host = "";
$user = "15";
$password = "lPXBFPqNg3f661JcegBY0N0dPXqUBdHXqj2cHf04PZgLHxT6z55e20ozojvMRvB8";
$comet = mysqli_connect($host, $user, $password, "CometQL_v1");

The code for sending a message to the pipe “simplechat” and event 'newMessage':

$query = "INSERT INTO pipes_messages (name, event, message)VALUES('simplechat', 'newMessage', '".$msg."')"; 
mysqli_query($comet, $query);

Step 3. Receive message from comet server

Subscription code to the pipe on comet server. This callback will be called when somebody sends message into channel `simplechat`

    cometApi.subscription("simplechat.newMessage", function(event){

Full chat code



Enter your comment. Wiki syntax is allowed: