PHP

PHP – What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet

php-articles-memory
php-articles

Regular HTTP:

  • Before you can understand these technologies, you have to understand classic HTTP web traffic first.
    1. A client requests a webpage from a server.
    2. The server calculates the response
    3. The server sends the response to the client.

Ajax Polling:

1.A client requests a webpage from a server using regular HTTP (see HTTP above).

2.The requested webpage executes JavaScript which requests a file from the server at regular intervals (e.g. 0.5 seconds).

3.The server calculates each response and sends it back, just like normal HTTP traffic.

 

Ajax Long-Polling:

1.A client requests a webpage from a server using regular HTTP (see HTTP above).

2.The requested webpage executes JavaScript which requests a file from the server.

3.The server does not immediately respond with the requested information but waits until there’s new information available.

4.When there’s new information available, the server responds with the new information.

5.The client receives the new information and immediately sends another request to the server, re-starting the process.

HTML5 Server Sent Events (SSE) / EventSource:

  • .A client requests a webpage from a server using regular HTTP (see HTTP above).
  • The requested webpage executes javascript which opens a connection to the server.
  • The server sends an event to the client when there’s new information available.
    1. .Real-time traffic from server to client, mostly that’s what you’ll need
    2. .You’ll want to use a server that has an event loop
    3. .Not possible to connect with a server from another domain

 

HTML5 Websockets:

  • A client requests a webpage from a server using regular http (see HTTP above).
  • The requested webpage executes JavaScript which opens a connection with the server.
  • The server and the client can now send each other messages when new data (on either side) is available.
    1. Real-time traffic from the server to the client and from the client to the server
    2. You’ll want to use a server that has an event loop
    3. With WebSockets it is possible to connect with a server from another domain.
    4. It is also possible to use a third party hosted websocket server, for example Pusher(https://pusher.com/) This way you’ll only have to implement the client side, which is very easy!
READ  How to get the full URL in PHP

Comet:

Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications.

What is long-polling and short polling ?

Short-polling:

Send a request to the server, get an instant answer. Do this every x seconds, minutes etc. to keep your application up-to-date. But: This costs a lot of requests.

Long-polling:

Send a request to the server, keep the connection open, get an answer when there’s “data” for you. This will cost you only one request (per user), but the request keeps a permanent connection between client and server up.

How to use:

To test, simply change the URL in client/client.js to the location of your server.php file, for local testing url: will do the job. Open the client/index.html to simulate the client.

While having the index.html opened in your browser, edit the data.txt on the server (and save it). You’ll see index.html instantly (!) getting the new content. Voila!

Simple Chat Using WebSocket and PHP Socket

  • The WebSocket is a feature of HTML5 for establishing a socket connections between a web browser and a server, once the connection has been established with the server, all WebSocket data (frames) are sent directly over a socket rather than usual HTTP response and requests, giving us much faster and persistent communication between a web browser and a server.
  • Let’s create a simple chat system using this cool technology (HTML5 WebSocket and PHP).

Getting Started with WebSocket

  • Client side WebSocket implementation is very easy, the entire code consist of few methods and events. Have a look at code below for example.
php code
//create a new WebSocket object.
websocket = new WebSocket("ws://localhost:9000/daemon.php"); 
websocket.onopen = function(evt) 
{
 /* do stuff */ 
}
; //on open event
websocket.onclose = function(evt) 
{ 
/* do stuff */ 
}
; //on close event
websocket.onmessage = function(evt) 
{
 /* do stuff */ }; //on message event
websocket.onerror = function(evt) 
{
 /* do stuff */ 
}
; //on error event
websocket.send(message); //send method
websocket.close(); //close method
  • To open the socket connection, we simply call new WebSocket(ws://SERVER URL), since WebSocket uses a different protocol for the connections,
  • we use ws://instead of http://, followed by host, port number and daemon script in your server:
READ  [Solved –10 Answers] How to get the client IP address in PHP

Right after opening the connection, we need to attach some event handlers that let us know status of connectivity, errors and incoming messages, for your references:

    • WebSocket(wsUri)— creates a new WebSocket object.
    • .onopen— Event occurs when connection is established.
    • .onclose— Event occurs when connection is closed.
    • .onmessage— Event occurs when client receives data from server.
    • .onerror— Event occurs when there is an error.
    • .send(message)— Transmits data to server using open connection.
    • .close() — Terminates existing connection
  • You can implement WebSocket with jQuery support in your webpage like this.
javascript code
JQUERY
$(document).ready(function()
{
    //Open a WebSocket connection.
    var wsUri = "ws://localhost:9000/daemon.php";   
    websocket = new WebSocket(wsUri); 
    //Connected to server
    websocket.onopen = function(ev) 
{
        alert('Connected to server ');
 }
    //Connection close
    websocket.onclose = function(ev) 
{ 
        alert('Disconnected');
 };
     //Message Receved
    websocket.onmessage = function(ev) 
{ 
        alert('Message '+ev.data);
}; 
    //Error
    websocket.onerror = function(ev)
 { 
        alert('Error '+ev.data);
};
     //Send a Message
    $('#send').click(function()
{ 
        var mymessage = 'This is a test message'; 
        websocket.send(mymessage);
 });
});

Serversent events (SSE):

  • Serversent events (SSE) is a web technology where a browser receives automatic updates from a server via HTTP protocol. SSE was known before as EventSource and first is introduced in 2006 by Opera.

Overview:

  • Server-sent events is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established.
  • They are commonly used to send message updates or continuous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream.

Comet:

  • Comet is a programming technique that enables web servers to send data to the client without having any need for the client to request it.
  • This technique will produce more responsive applications than classic AJAX. In classic AJAX applications, web browser (client) cannot be notified in real time that the server data model has changed.
  • The user must create a request (for example by clicking on a link) or a periodic AJAX request must happen in order to get new data fro the server.
READ  PHP define() vs const

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

1 Comment

Click here to post a comment