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).
Old browsers do not support WebSockets, you need latest browser that supports HTML5 WebSocket features, Please see caniuse.com to find-out all WebSocket supported browsers.
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.
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:
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.
As explained in examples above, we start by creating a WebSocket object, attaching event handlers and then using websocket.send() method to send the data. Since we are sending a collection of chat values, such as user name, message, color etc, we’ll convert our data to JSON format before sending to server.
Below is our HTML for the chat system, it comes with some basic styling, I have not included the CSS part here, but you should find it in sample file.
Chat Server using PHP Socket
Ok! Now we have our chat page ready to connect to server, but we also need to create a WebSocket server that runs permanently (no time-outs), performs WebSocket handshaking, send/receive data from chat page and handles multiple clients, for that we will create a daemon script in PHP. Everyone knows PHP is mostly used to create dynamic webpages, but most of us didn’t know that we can also create daemons (that run in the background) using nothing but PHP.
Install WebSocket Server
Install a local web server such as WAMP or XAMPP. I am using XAMPP server on Win-XP, it lets me use shell option to start my daemon script. I am not sure if WAMP has the same feature, but you can follow Dani’s solution here to run this server script. If you want to implement it on your website, first check whether your host allows you to run daemon scripts and shell commands.
PHP Socket Steps
We will be using PHP socket to create our WebSocket Chat server, Basically our PHP Chat server should do the following.
- Open a socket.
- Bind to a address.
- Listen incoming connections.
- Accept connections.
- WebSocket Handshake.
- Unmask/Encode data frames.
Open a socket:
First we create a socket with PHP socket_create(Domain, Type, Protocol) like this:
Bind to a address:
Bind the name to the socket, this has to be done before a connection is established using socket_connect() or socket_listen().
Listen incoming connections:
Once the socket is created, we want our server to listen to incoming connection on that socket.
This function will accept incoming connections.
Client has to introduce itself by sending a WebSocket handshake request to establish a successful connection with server, a handshake request contains a Sec-WebSocket-Key a base64 encoded randomly generated 16-byte value. And the server reads the key, attaches magic string “258EAFA5-E914-47DA-95CA-C5AB0DC85B11”, hash key with SHA1, returns the key in Sec-WebSocket-Accept encoded with base64.
Handshake response with PHP :
Unmasking/Encoding data frames.
After the handshaking, client can now send and receive messages, but the messages sent are all encrypted, so if we want to display them, each data frame needs to be unmasked as described here
Starting Chat Server
It’s time to download the sample files by clicking download button below, you should find 2 PHP files, index.php and server.php. Using your Shell command-line interface in XAMPP, start WebSocket chat server by typing :
Once the server starts, you can navigate to index.php page using your browser and start test chatting.