PHP Ratchet is a popular library for building WebSocket servers in PHP, allowing real-time communication between clients and servers. Setting up a Ratchet WebSocket server in a live hosting environment may seem tricky at first, but it’s actually quite manageable with the right steps.
Running a PHP Ratchet WebSocket server on live hosting might seem challenging at first, but with the right setup and tools like Supervisor, it’s manageable. By following the steps above, you’ll be able to deploy and run your WebSocket server efficiently in a production environment, enabling real-time communication for your applications.
Here’s a step-by-step guide to get you started with running a PHP Ratchet WebSocket server on a live hosting environment.
Steps to Configure Your WebSocket Server
1. Set Up a Reverse Proxy
To handle WebSocket traffic effectively, configure your web server (Nginx) to act as a reverse proxy on port 6666. This setup ensures that WebSocket connections are properly routed to your PHP Ratchet server, here is the code of below reverse proxy code
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1:6666;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Increase timeout settings if necessary
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
You need to create a new configuration for Nginx that will direct WebSocket requests to your server. This involves specifying the correct port and ensuring that Nginx properly forwards WebSocket traffic as per defined above.
1.2 Enable and Test the Configuration
After setting up the above configuration, make sure to enable it and test that Nginx is correctly handling the WebSocket connections. Reload Nginx to apply the changes.
2. Allow Port 5869 in Your Firewall
Ensure that your firewall permits traffic on port 5869. This is essential for allowing external WebSocket connections to reach your server. Use the appropriate firewall commands to open the port and verify that it is not blocked or used by another service, run below command to allow port in vps server
ufw allow 5869
3. Install and Configure SSL
To secure WebSocket connections, you need to set up SSL/TLS on your reverse proxy. This will encrypt the data exchanged between clients and your WebSocket server.
4. Run Websocket Server in Background
One of the challenges of running a WebSocket server is ensuring it stays running even after SSH disconnects or a crash. For this, you can use Supervisor, a Linux process control system, to manage your WebSocket server.
- Create New file : /etc/systemd/system/yourfileName.service
[Unit]
Description=WebSocket Server
[Service]
ExecStart=/usr/bin/php8.1 path/to/script.php
Restart=always
User=root
Group=root
StandardOutput=append:/var/log/websocket.log
StandardError=append:/var/log/websocket_error.log
[Install]
WantedBy=multi-user.target
2. Run Below code to start websocket server in background
service websocket start
3. Run Below code to stop websocket server in background
service websocket stop
4. Run Below code to restart websocket server in background
service websocket restart
4. Run Below code to check status of running websocket server in background
service websocket status
3. Create Demo PHP WebSocket Ratchet code
config.php
<?php
const websocket_host = "localhost";
const websocket_port = "6666";
local
const client_websocket_url = "ws://".websocket_host.":".websocket_port;
// live
#const client_websocket_url = "wss://".websocket_host;
server.php
<?php
require_once __DIR__."/config.php";
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require __DIR__ . '/vendor/autoload.php';
class MyChat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo "Chat server started on ".websocket_host." on ".websocket_port ."\n";
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from != $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
// Run the server application through the WebSocket protocol on port 8080
$app = new Ratchet\App(websocket_host, websocket_port);
$app->route('/', new MyChat, array('*'));
$app->run();
index.php
<?php require_once __DIR__."/config.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var conn = new WebSocket('<?= client_websocket_url ?>');
conn.onmessage = function(e) { console.log(e.data); };
conn.onopen = function(e) { conn.send('Hello Me!'); };
</script>
</body>
</html>
Best Practices for Running WebSocket in Production
Use HTTPS and WSS: For security reasons, always run WebSocket over WSS (WebSocket Secure), which requires an SSL certificate.
Monitor Server Load: WebSocket connections can consume resources. Ensure you monitor your server to handle high traffic.
Set Proper Timeouts: Ensure there are timeouts for idle connections to free up resources.
Scale with Load Balancers: For larger applications, you may need to use a load balancer to distribute WebSocket connections across multiple servers.
Download Source Code click here.
Watch the Video Guide
For a step-by-step visual guide, watch our video tutorial. It covers everything from installation to configuration and testing.
By following these instructions, you’ll have a live PHP Ratchet WebSocket server running smoothly, allowing real-time communication in your web applications. If you have any questions or run into issues, feel free to leave a comment below or reach out for support.