Next article

Laravel’s event is easy to implement and provides a simple observer practice. Allowing application user to subscribe and listen to various events that occur in...

WebSocket Chat

WebSocket is a correspondences convention for a constant, bi-directional, full duplex TCP association from a client’s internet browser to a server.

The WebSocket convention empowers association between a web customer, (for example, a program) and a web server with lower overheads, encouraging continuous information exchange from and to the server.

WebSockets can be exceptionally advantageous for building real-time correspondence or information spilling applications on the web, for example, talk applications and applications that stream pictures or different kinds of media.

Why WebSockets instead of HTTP(S)?

With WebSockets you can build up a persistent connection, which takes into account bidirectional correspondence among client and server. These days, you will generally discover REST constructed APIs in light of the web, which is based upon HTTP. These APIs are devoured as pursues: The customer asks for a page or asset and the server reacts (ask for response).
WebSockets is having below advantages over HTTP:

1. Real-time Communication

WebSockets are bi-directional, which means the server can send information to a program without requesting it. This implies applications that require the continuous trade of data should be possible over a standard web convention. Since WebSockets needn’t bother with the HTTP ask for when making an association, there is a noteworthy decrease of pointless HTTP header activity.

With a WebSocket, you never again need to sit tight for a demand before it sends new information; it will naturally send the information to the customer the minute there is new data.

2. Less overhead

HTTP is a stateless protocol, thus the overhead of the HTTP header is added to every single message, which can get quite large in size.

Moreover, the HTTP connection will usually only keep alive for a certain amount of requests and will be closed after some time of being idle.

Thus connections will quite frequently have to be reestablished, which introduces an initial setup time due to the TCP 3-Way Handshake (and exchanging certificate and key pairs in case of HTTPS).

3. Stream processing

Using WebSockets binary data of arbitrary size can stream essentially between client and server.

Let’s see PHP Chat application implementation using Web Socket.
WebSocket implement at Client Side

At client side, we will have to write some HTML code to create chat interface and jQuery code which contains method and events of the WebSocket.

  • Create a file – index.php
  • Add below PHP code that will pick up random color for the Username to display in Chat window.
  • Add HTML for Chat interface which will display Chat panel and Fields to enter User name and Message.
  • Below code will use to open the web socket connection. As WebSocket uses different protocol for connection, we are using ws:// in place of http://.var wsUri = “ws://localhost:9000/socketchat/server.php”;
    websocket = new WebSocket(wsUri);

After opening the socket connection, we have to write some event handlers that will return status of socket connection, errors, and incoming messages.

//create a new WebSocket object.
websocket.onopen = function(evt) { /* do stuff */ }; //call when socket connection initiate
websocket.onclose = function(evt) { /* do stuff */ }; //call when socket connection colsed
websocket.onmessage = function(evt) { /* do stuff */ }; //call when client receives data from server
websocket.onerror = function(evt) { /* do stuff */ }; //call when any error
websocket.send(message); //call when client send data to server
websocket.close(); //call to close socket connection

  • We will write methods to send the message to WebSocket on click of Send button from the chat box.

send_message() method will call when user will click on Send button or Press Enter in Chat message text box. This method will convert chat message, username, color data into JSON format and send it to WebSocket server.

So now Chat page is ready which will connect to server. We also need to implement WebSocket Server in PHP that will run permanently, send and receive data from Chat Page.

This server will run in background to keep WebSocket connection established.

  • If Sockets extension is not enabled, enable extension (extension=php_sockets.dll) on server from php.ini file.
  • Create server.php file
  • Need to create a socket, binding address to the socket, listen to incoming connections with below code.
  • Then we will write code to accept new connections, remove disconnected clients from list, and send messages to connected clients.

Below function will send messages to each connected clients.

  • Being a PHP developer you are surely aware that now PHP code will check new connection request if any new connection request then it will accept the request and perform a handshake with new socket resource. And then send acknowledgment about connectivity.
  • Once handshake performed successfully, the client can send and receive messages. Data which client will sent will be encrypted, so data need to mask and unmasked to send and receive it to the client.

We are done with Chat server implementation, now we have to start Chat server.
Start Chat Server

  • Open command prompt and run below command to start chat server.

php -q D:\Projects\xampp\htdocs\socketchat\server.php

  • Now you can open index.php (http://localhost/socketchat/index.php) from browser, that will display Chat window with message that socket is connected. And now user can start using Chat functionality.


When there is need of real-time data, WebSocket is the solution in place of HTTP requests. Chat is just an example here, but we can use WebSocket for other requirements also like display tasks add/update/delete real time, display tasks and status updates as soon as that trigger.


  • Leave a message...