kosar501 / phpwebsocket
a simple package interaction websocket server and client
Requires
- php: >=7.4
- ext-json: *
- ext-zmq: *
- cboden/ratchet: ^0.4.4
- react/socket: ^1.16
- react/zmq: ^0.4.0
- symfony/console: ^5.4
- vlucas/phpdotenv: ^5.6
This package is auto-updated.
Last update: 2025-03-16 17:46:04 UTC
README
Overview
Real-time messaging platform utilizing WebSocket for bidirectional communication between clients and a ZeroMQ-powered backend for scalable, asynchronous message distribution. This project enables efficient and low-latency communication across multiple connected clients, with ZeroMQ handling high-throughput messaging and WebSocket ensuring real-time updates in a responsive web interface.
WebSocket Server: Listens for WebSocket connections and broadcasts messages to connected clients.
Installation
Step 1: Clone the Repository
Clone the repository to your local machine:
git clone https://github.com/kosar501/PhpWebSocket.git
cd your-project-folder
Step 2: Install Dependencies
composer install
Step 2: Install Dependencies
composer install
Running the Server
There are two main components in the system: the WebSocket server and the Redis queue consumer. You can run both components as separate processes, and they will be managed using Supervisor.
1: Running WebSocket Server Along With ZMQ
1.1: Manually (for development or testing)
php server.php
1.2: Using Supervisor (Recommended for production)
[program:websocket-server] command=php /path/to/your/project/server.php autostart=true autorestart=true stderr_logfile=/var/log/websocket_server.err.log stdout_logfile=/var/log/websocket_server.out.log
After adding this configuration, update Supervisor:
supervisorctl start websocket-server
Start the WebSocket server:
supervisorctl start websocket-server
If you encounter issues, restart the processes via Supervisor:
supervisorctl restart websocket-server
How to Use
You can use the Client class to send messages to the WebSocket server through Redis. This class sends messages to the Redis queue that the consumer will process.
Server Side:
Example:
$client = new MessagePublisher(); // Prepare the message as an associative array $message = json_encode(['topic' => 'news', 'content' => 'This is a test message']); $client->sendMessage($message);
On the Client Side (Web Browser):
Example:
You can check examples folder
const socket = new WebSocket('ws://127.0.0.1:5555'); socket.onmessage = function(event) { const message = JSON.parse(event.data); console.log('Received message:', message); // Now you can access the message properties like message.action, message.username, etc. };