If you are using a WebSocket server from PieSocket, you are lucky because we let you publish messages to our WebSocket channels through a REST API as documented here: https://www.piesocket.com/docs/3.0/php
What about an external WebSocket channel, or what if for some reason you want to connect to the PieSocket channel through a PHP WebSocket client and not the REST API.
In this tutorial, we will create a script that runs in a Linux/Mac/Windows terminal and acts as a WebSocket client to connect to any WebSocket server.
For testing purposes, we will use PieSocket’s publicly available WebSocket Server
1 |
wss://demo.piesocket.com/v3/channel_1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm¬ify_self |
Let’s begin building our shiny new PHP WebSocket Client application.
Start by creating an empty directory for our project
1 |
mkdir php-websocket-client |
Change working directory to the newly created project directory
1 |
cd php-websocket-client |
For the next step, you need composer in your system, if you do not have it already, install composer.
Next, Install the “Textalk/websocket-php” library into your application
1 |
composer require textalk/websocket |
This will place composer.json and composer.lock files into your current directory and download dependencies into the vendor folder.
Now it’s time to create the script to connect to a WebSocket server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php include "./vendor/autoload.php"; $client = new WebSocket\Client("wss://demo.piesocket.com/v3/channel_1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm¬ify_self"); $client->text('Hello PieSocket!'); while (true) { try { $message = $client->receive(); print_r($message); echo "\n"; } catch (\WebSocket\ConnectionException $e) { // Possibly log errors print_r("Error: ".$e->getMessage()); } } $client->close(); ?> |
We include the vendor/autolaod.php file to load the dependencies we downloaded using composer into our script.
Then, we connect to the WebSocket server and run an infinite loop so the script keeps running to listen to the incoming messages.
Time to run the script, open a terminal, and fire up the following command
1 |
php client.php |
You should see incoming messages in your terminal now.
You can use PieSocket’s WebSocket Tester to send messages to the WebSocket server and they should appear in your terminal.
You can find the source code shown above in this git repository: https://github.com/piesocket/php-websocket-client-example
Hope this helps, let us know your questions and feedback by leaving comments below!