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 Show 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
Let’s begin building our shiny new PHP WebSocket Client application. Start by creating an empty directory for our project
Change working directory to the newly created project directory For the next step, you need composer in your system, if you do not have it already, install composer.
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.
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 You should see incoming messages in your terminal now. 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! Can I use WebSockets with PHP?You can use and deploy a WebSocket server in a PHP server today. How configure WebSocket in PHP?To implement WebSocket with PHP, you have to install an additional module like Swoole. You have more than one module that allows you to implement WebSocket service in PHP, in this tutorial I'm going to use Open Swoole implementation by SwooleLabs considering that Open Swoole includes support for WebSocket. How do I run WebSockets?To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://javascript.info"); There's also encrypted wss:// protocol. It's like HTTPS for websockets. What are WebSockets in PHP?What are WebSockets? Websockets are low-latency (or fast), persistent connections between a server and one or more clients. Unlike AJAX requests, WebSockets are bi-directional (push-pull), meaning that both the client and server can listen to each other in real-time and respond to any changes. |