PHP Websocket Library – Two way real time communication

From the born of www era and the implementation of JavaScript and ajax, web is looking for a solution to find out real time client-server bidirectional communication. Now It is [...]

View demo Download source

From the born of www era and the implementation of JavaScript and ajax, web is looking for a solution to find out real time client-server bidirectional communication. Now It is been suggested to include within HTML5 and has been in full developmental phase. Although it not yet recommenced by W3, it is been wildly implemented in most of modern web browsers including Google Chrome,Opera,Firefox and safari.

The Need for Real-time communication for web-applications.

Some of web applications need real time update of data which used for real-time communication. Most of the websites accomplish this task by ajax. Solutions like long time ajax pooling is also used. But these solutions are not effective as they use more server and communication resources.

Simple HTTP protocol is work as request and response. Where client request server to retrieve a webpage and server respond with webpage. But this method comes to difficulty when server wants to send some information to client.

Need for websockets . Communication gap between server and client.

Need for websockets . Communication gap between server and client.

one solution for this problem is to use long time ajax pooling in which client send a request to server and server hold that request util some data need to send to that client. But this is not and effective method since it consume lot of server and network resources.

Solution? one word ‘Websocket‘. This is a communication protocol which allows bidirectional real-time communication between client and server. In simple words, Once connection is established, server->client and client->server communication is possible in real-time  Which do not require separate TCP connections for each communication.

Need for websockets .

Need for websockets .

Using this library you can implement you web app using web sockets in a few steps.  Download package include an demo application called ‘instant Chat’ which uses web sockets library to implement realtime chat communication.

PHP Websoket library.

This websocket library used for creating php websocket server. This library can be used with following steps.

1. Download PHP Websocket library.

View demo Download source


2. Copy ‘lib’ folder in to you application, and include library files into your web application

[php]

include “./lib/Socket.php”;
include “./lib/Server.php”;
include “./lib/Connection.php”;

[/php]

3. Create websockets server object.

[php]

$server = new Server(‘0.0.0.0’, 8000, false);
$server->setHook($myclass);
$>server->run();

[/php]

Server class contains three parameters Server IP and Server port. The setHook function set the hook for Websocket Server. The hook is a object of user defined class which can be used to handle Websocket Server events. Web sockets server events include, clientConnect, clientDisconnect and dataReceive. This events is explained in following step.

4. Define WebSoket handler.

This setup define the handler class which handle websocket events.

[php padlinenumbers=”auto”]

class Application {

public $server;

public function __construct(){
$this->server = new Server(‘0.0.0.0’, 8000, false);
$this->server->setHook($this);
$this->server->run();
}

 

/* Fired when a socket trying to connect */
public function onConnect($connection_id){
/* Your code here */
}

/* Fired when a socket disconnected */
public function onDisconnect($connection_id){
/* Your code here */
}

/* Fired when data received */
public function onDataReceive($connection_id,$data){
/* Your code here */
}

/* Used to send data to particular connection */
public function sendDataToConnection($connection_id,$action,$data){
$this->server->sendData($connection_id,$action,$data);
}

}

[/php]

HANDLER FUNCTIONS

  • onConnect – This function fired when a client establishes a connection. <code>$connection_id</code> is the uniue id which can be used to identify a connection.
  • onDisconnect – This function fired when a client disconnects a connection.
  • onDataReceive – This function fires when data is received from already established connection.
  • sendDataToConnection this function can be used to send data to a connection.

All the communcation b/w client and server is an JSON encoded array which contains to elements ‘action’ and ‘data’. In which action specify the type of request.

5. Start WebSockets Server.

Once handler functions are defined you can start server. Eg,

[php]

$app = new Application();

[/php]

you can make sure that server is started properly using netstat -ntlp | grep LISTEN which list opened port on server. Make sure that port 8000 is in the list.

[bash]
jithin@jithin-Studio-1558:/var/www/techzonemind$ php server.php
2014-03-17 21:56:35 [info] Server started listening to port 8000

[/bash]

6. Connect to websokets server using Javascript.

You can use WebSocket object in JavaScript to connect to a websockets server. Before you start please make sure that your browser supports to websockets.

[javascript]

serverUrl = ‘ws://www.techzonemind.com:8000/demo’;
if (window.MozWebSocket) {
socket = new MozWebSocket(serverUrl);
} else if (window.WebSocket) {
socket = new WebSocket(serverUrl);
}

socket.binaryType = ‘blob’;

/* Fires when websocket get connected */
socket.onopen = function(msg) {
return true;
};

/* fires when a message received from server */
socket.onmessage = function(msg) {
response = JSON.parse(msg.data);
return true;
};

/* fires when disconnected from server */
socket.onclose = function(msg) {
return true;
}
/* You can use following function to send data to server. */
socket.send(JSON.stringify(payload));

[/javascript]

 

You can test demo application using following simple steps.

1. Make sure that Apache listen to Web-sockets port 8000.

[bash]
netstat -ntlp | grep LISTEN
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 3850/php

[/bash]

2. Start WebSockets server.

[bash]
jithin@jithin-Studio-1558:/var/www/techzonemind$ php server.php
2014-03-17 21:56:35 [info] Server started listening to port 8000

[/bash]

which start websockets server and listen to port 8000

3. Load HTML page on WebBrowser. And start use the chat application.

If you have any clarification regarding the topic or need any improvemts/mistakes/bugs please provide details below.

Next:

Tagged with:

  • Connect with :