Rabikant
Posted on November 25th
Build a WebSocket Client in PHP
"Let's Build a WebSocket Client in PHP"
What are WebSockets?
WebSocket is a protocol which can construct full-duplex communication over a single connection between the client as a browser and the server. This implies that both the client and the server can exchange messages with each other at one time without necessarily becoming connected again to exchange messages in the next time. WebSockets differ from HTTP protocol in which a client has to request data from the server then close the connection.
WebSockets were standardized by the IETF under RFC 6455 and work in all current modern web browsers. It starts with an HTTP hand shake where the client starts a request to upgrade the connection to a websocket. After this first step, the connection changes with a WebSocket that is established and remains active until one part, either the client or server, decides to terminate it. This upgrade mechanism makes it possible to build WebSockets on top of HTTP and it is smooth if an application was initially HTTP based.
WebSockets are particularly good for the apps where live update could be pushed through the server without an explicit poll. Ordinary client server based applications frequently send messages to the server to check if there is new data available for communication in actual time. Polling is a very costly process and this can have time implications as the following process takes time to be complete. On the other hand, WebSockets enable the actual push of information from the server to the client at once, making it a more efficient mechanism in handling real time data.
It is now possible to point to several kinds of applications where the advantages of WebSockets are obvious. For example, take a case in chat applications, we often have two users and when two user are chatting, every message passed between them has to be delivered, through WebSockets in real time manner. Online gaming also significantly profits from WebSockets since players need information on the game status and moves in real-time. Just as trading platforms are executing trades in real-time they depend on WebSockets to deliver users up-to-date price data with which to make a financial decision.
The WebSocket flow is divided into frames; these are general packets of data which may communicate whether the data they contain are text, binary, or are some control frame (for example, for breaking the connection). Websockets hence further the capability of having high frequency messages, as the light framing structure minimizes overhead as compared to ur http with heavier headers.
But absolutely not without their problems. They need companion on both client side and server side, this may not be a viable as far as some compuses are concerned. In the same vain, due to the fact that the connection is always open, WebSocket connections are at risk of security threats such as unauthorized access or attack leveraging on the fact that the connection stays open. WebSockets use the web security model for communication; however, it is common to encrypt the WebSocket connection using what is known as WebSocket Secure (WSS) over Transport Layer Security (TLS), so any sensitive information being passed will remain safe.
WebSockets are also highly scalable, which puts them in a perfect place to deal with applications that deal with thousands of connections. Nevertheless, they have more load on the server side owing to the fact that the connections remains open most of the time. While HTTP request is truly stateless, WebSocket on the other hand needs the server to maintain a connection to each conversation which is resource intensive in terms of memory and CPU utilization.
In conclusion, WebSockets offer a powerful solution for real-time, bidirectional communication, making them ideal for applications that demand low latency and immediate updates. While they introduce challenges in terms of resource management and security, WebSockets provide a versatile and efficient alternative to traditional HTTP for scenarios where real-time data transfer is essential.
Why Choose PieSocket?
PieSocket offers several advantages over building and maintaining your own WebSocket server:
- Simplifies Development: PieSocket WebSocket service is meant to be easily integrated and requires very little configuration. You don’t have to bother with the technical details of servers and setting up, scaling, or SSL connections.
- Built-in Security: PieSocket has features that enable use of Secure Sockets Layer encryption, and admin and user authentications and authorizations; this allows data passed via WebSocket connections to be secure. Such security features are in place as a measure against the main WebSocket threats include unauthorized WebSocket access and WebSocket message interception.
- High Performance and Scalability: Currently PieSocket utilizes cloud-based architecture that connections are fast, minimal latency yet fully packed with throughput. This is important for applications that demand quick response, like a stock exchange floor, or streaming services.
- Reduced Maintenance Overhead: WebSocket server means uptime, applying patches and making sure the server scales with the load. PieSocket handles these things to ensure your team can concentrate on building your application.
Explanation of the Code
Let’s walk through the provided PHP code, which uses the PieSocket service for WebSocket communication.
Setting Up the Code
Before running the code, ensure you have installed the websocket-php package via Composer:
composer require textalk/websocket
This library provides the WebSocket\Client class, making it easy to connect and communicate with WebSocket servers in PHP.
Code Walkthrough
<?php
require dirname(__FILE__) . '/vendor/autoload.php';
use WebSocket\Client;
- require dirname(FILE) . '/vendor/autoload.php';: This line loads Composer’s autoloader, which registers all the necessary libraries and classes that were installed via Composer.
- use WebSocket\Client;: Imports the Client class from the WebSocket namespace, which is provided by the websocket-php library. This class simplifies connecting to and interacting with WebSocket servers.
try {
// Replace 'your-channel-id', 'your-api-key', and 'your-api-endpoint' with your PieSocket details
$channelId = "2";
$clusterId = "free.blr2";
$apiKey = "B9UKgvptNTWrZxfCUTquFp7nKVsYqu2LtmBao5Jg";
$endpoint = "wss://$clusterId.piesocket.com/v3/$channelId?api_key=$apiKey¬ify_self";
- $channelId = "2";: The PieSocket channel ID, which uniquely identifies the channel within PieSocket. Channels are communication spaces where messages are exchanged between clients.
- $clusterId = "free.blr2";: The cluster ID where the WebSocket server is hosted. Clusters are regions where PieSocket provides WebSocket endpoints.
- $apiKey = "B9UKgvptNTWrZxfCUTquFp7nKVsYqu2LtmBao5Jg";: The API key associated with your PieSocket account, used to authenticate your connection.
- $endpoint = "wss://$clusterId.piesocket.com/v3/$channelId?api_key=$apiKey¬ify_self";: Constructs the WebSocket URL with your cluster, channel ID, and API key. The wss:// protocol specifies a secure WebSocket connection (encrypted with SSL), and notify_self allows the client to receive messages it sends (useful for testing).
// Connect to the PieSocket WebSocket server
$client = new Client($endpoint);
- $client = new Client($endpoint);: Instantiates a new Client object using the PieSocket WebSocket URL. This establishes a connection to the WebSocket server.
// Send a message to the server
$client->send("Hello PieSocket Server!");
- $client->send("Hello PieSocket Server!");: Sends a message string to the PieSocket server. In this case, it’s a simple “Hello” message, but in real applications, this could be any data, such as JSON for structured messages.
// Receive a response from the server
$response = $client->receive();
echo "Response from server: $response\n";
- $response = $client->receive();: A request, which waits for a message that originated from the server. In chat or notification system this might be a reply to another client or a reply acknowledgment from the server.
- echo "Response from server: $response\n"; This is useful for debug and analyze response from server.It only prints the server response to the terminal as shown below;
// Close the connection
$client->close();
} catch (Exception $e) {
echo "Could not connect to PieSocket server: ", $e->getMessage(), "\n";
}
- $client->close();: Forces the WebSocket connection to close.
- catch (Exception $e): Shows any errors that may have arisen like connection failure, or invalid API credentials.
- echo "Could not connect to PieSocket server: ", $e->getMessage(), "\n"; Show the exception and its message so that if an exception is caught, one knows what went wrong, e.g., connection problems, API key problem, etc. Prints the error message in case an exception is caught.
More recommendations:
- Securing Your API Key: You must not share your API with any third parties. One should never put sensitive keys right in the code which might be seen by others or stored in the public repositories. Some developers recommend people store API keys into environment variables.
- Channel Management: PieSocket makes it have it where each channel is capable of being used to handle one or multiple groups. For example, a chat app may have sub-branches; such as different group chats. Consequently the ‘channelId’ should be used to restrict access to particular data streams to specific users.
- Message Handling: PieSocket uses WebSocket technology to serve messages with JSON formats by default. Incoming messages can also be structured for receive in JSON format as it eases handling of structured data on the client making.
Error Handling:
Always implement error handling when working with network connections. Connection errors, authentication errors, and other issues can disrupt your application, so robust error handling helps to keep your application resilient.
Here is the code for the app.
<?php
require dirname(__FILE__) . '/vendor/autoload.php';
use WebSocket\Client;
try {
// Replace 'your-channel-id', 'your-api-key', and 'your-api-endpoint' with your PieSocket details
$channelId = "2";
$clusterId = "free.blr2";
$apiKey = "B9UKgvptNTWrZxfCUTquFp7nKVsYqu2LtmBao5Jg";
$endpoint = "wss://$clusterId.piesocket.com/v3/$channelId?api_key=$apiKey¬ify_self";
// Connect to the PieSocket WebSocket server
$client = new Client($endpoint);
// Send a message to the server
$client->send("Hello PieSocket Server!");
// Receive a response from the server
$response = $client->receive();
echo "Response from server: $response\n";
// Close the connection
$client->close();
} catch (Exception $e) {
echo "Could not connect to PieSocket server: ", $e->getMessage(), "\n";
}

Complete Code
The project is available on our GitHub : https://github.com/piehostHQ/php-ws-client
