Rabikant Singh
Posted on November 15th
How To Connect To WebSockets With PHP
"Lets learn how to connect to WebSockets with PHP"

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.
Connecting to PieSocket’s WebSocket Server
For testing purposes, we will use PieSocket’s publicly available WebSocket Server
wss://demo.piesocket.com/v3/channel_1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm¬ify_self
Let’s begin building our shiny new PHP WebSocket Client application.
Setting Up Our Project
Start by creating an empty directory for our project
mkdir php-websocket-client
Change working directory to the newly created project directory
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
composer require textalk/websocket
This will place composer.json and composer.lock files into your current directory and download dependencies into the vendor folder.
Let's Write The Code
Now it’s time to create the script to connect to a WebSocket server.
<?php
include "./vendor/autoload.php";
$client = new WebSocketClient("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 (WebSocketConnectionException $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
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!
