Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Create PHP Live Chat With Websocket

INTRODUCTION
REAL-TIME CHAT BUSINESS

Welcome to a tutorial on how to create a PHP live chat application with Websocket. While doing some research on real-time PHP applications and WebSockets, several live chats turned up. Shockingly though, most of them are either paid ones or run on AJAX long polling.

Not quite what I was looking for, and an evil thought turned up to create and sell one of my own… But no. My Jedi blogger side still took over, and hence the purpose of this guide – To share how WebSockets work, how we can use it for real-time applications, and that the stone age of the Internet is over. Read on to find out!

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Section A
The Overview

Section B
Websocket Basics

Section C
Server-Side Script

Section D
Client-Side Script

Extra
Useful Bits & Limitations

Extra
Source Code Download

Closing
What’s Next?

SECTION A
THE OVERVIEW

Before we go into any code, let us start with a section on an overview of the system, and what you will need.

SYSTEM OVERVIEW

There are 3 parts to this live chat system:

  • Database – To store the chat.
  • Server – The PHP scripts that will host the chat.
  • Clients – The HTML/Javascript that will connect to the server.

AJAX LONG POLLING VS WEBSOCKET

Remember that “AJAX long polling” is mentioned in the introduction above? What is it and how is WebSocket different? Well, long story short:

  • AJAX is an asynchronous connection to the server – Once you get the data, the connection is closed. Long polling works by firing multiple AJAX requests to the server over a long period of time to simulate a real-time connection.
  • A socket, on the other hand, is a “permanent” connection – Once you connect to the server, you remain connected until you manually disconnect.

So yep, some of you sharp code ninjas should have figured this out. An “always on” WebSocket connection works better in the context of real-time applications.

PHP SOCKET EXTENSION

For this project to work, you need to enable the socket extension. Look under the extensions section of your php.ini file and enable it accordingly:

php.ini
extension=sockets

SECTION B
WEBSOCKET BASICS

WebSockets can be very daunting to beginners, so let us begin with a very simple example and crash course. Special thanks to Vladimir Kovpak for this awesome WebSocket example.

SERVER-SIDE PHP SCRIPT

1-server.php

We begin the project by creating the server-side script:

  • This script will open up a socket at your specified address, port number, and listen for client connections.
  • The somewhat painful part to understand is that PHP does not support WebSockets out-of-the-box… We will have to manually serve our own handshake headers to the clients.
  • You can read more about the WebSocket headers at MDN web docs if you want.
  • The final part is really isn’t that much of a mystery. We simply keep this script running and output a dummy timestamp to any connected client in an infinite while (true) loop.

CLIENT JAVASCRIPT

1-client.html


  
    Simple WebSocket Example

Next, this is as simple as it gets on the client side. All we need to do is to connect to the server socket, and show the updates as they stream in.

START YOUR ENGINES!

With scripts on both server and client side ready, we can now launch the script from the command prompt (or terminal). 

D:\http\test>php 1-server.php

Then, access the client script from your web browser.

SECTION C
SERVER-SIDE SCRIPT

Now that you have a good idea on how WebSocket works, let us “upgrade” the scripts to turn it into an actual live chat. 

THE SCRIPT

2-chat-server.php
0) {
    /* (5) LISTEN FOR DATA INPUT */
    foreach ($clients as $c) {
      if (($chat = socket_read($c, 5000)) !== false) {
        // The client message is masked!
        // We need to unmask it to get back the original message
        $buffer .= unmask($chat) . "
"; if ($verbose) { echo "Buffer - " . $buffer . "\r\n"; } } } /* (6) UPDATE CHAT TO ALL CONNECTED CLIENTS */ if ($buffer != "") { $chat = chr(129) . chr(strlen($buffer)) . $buffer; if ($verbose) { echo "Output Buffer - " . $chat . "\r\n"; } foreach ($clients as $c) { socket_write($c, $chat); } $buffer = ""; } } } ?>

THE EXPLANATION

Holy cow. Some of you guys might be foaming in the mouth at the “small improvements” this server-side script has… But rest assured, how it works is still fundamentally the same. The only exception is that instead of being a dumb “output timestamp”, we added features to allow multiple client connections, and allow 2-way communications. Here’s a summary:

  1. As usual, we begin with the settings and a support function.
  2. Create and open a WebSocket.
  3. Create an endless loop.
  4. Listen for new connections, and do the WebSocket magic handshake thing.
  5. Listen for chat input from the users, and store them into a buffer.
  6. Output the chat buffer to all connected clients to update them.

SECTION D
CLIENT-SIDE SCRIPT

Finally, we shall update the client-side script as well, add a function to send messages to the server.

THE SCRIPT

2-chat-client.html


  
    Simple WebSocket Example

THE EXPLANATION

Holy cow. Some of you guys will be foaming in the mouth again from the “improvements” made in the Javascript. But keep calm and look carefully.

  • We have only added a simple form to receive text input for the chat.
  • Things may look complicated, but we are just arranging things better by putting all the chat related stuff into var chat.
  • The working principals are the same as the above simple example.
  • Connect to the server, enable the chat form, and update the view as we receive more messages from the server.

See, it’s not so bad.

RESTART YOUR ENGINES

All that remains is the same as previous – Run the server-side script in the command line, and access the client-side script in your web browser.

EXTRA
USEFUL BITS & LIMITATIONS

That’s all for this project, and here is a small section on some extras that may be useful to you.

REFERENCES

If you want to learn more about sockets, here are the official links:

  • PHP Sockets
  • MDN WebSocket

LIMITATIONS

This chat script is extremely simplistic. There are no user identifications, nor does the server-side does any detection if the user has closed connection. There is no error management as well. All of these are kind of up to everyone’s project needs, and I will not add any more to it… Nor give away free lunches.  

EXTRA
DOWNLOAD

Finally, here is the download link as promised.

QUICK START

Skipped the entire tutorial? Here are a few quick steps to set up the example:

  • Download and unzip into the project folder, there are 2 sets of codes in the zip file.
  • 1-server.php and 1-client.html is not a live chat, but a simple demonstration of WebSocket.
  • 2-chat-server.php and 2-chat-client.html are the simple live chat.
  • Run 2-chat-server.php in the command line.
  • Access 2-chat-client.html in your web browser.

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. That took quite a lot of research, work, and I can easily see why some people are charging money for it… But I hope that this has helped you in your project, and if you want to share anything, please feel free to comment below. Good luck and happy coding!

The post How to Create PHP Live Chat With Websocket appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Create PHP Live Chat With Websocket

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×