I just started to learn websockets with "Workerman" library on my nginx server, and i ran into a problem.
I tried some examples, so I think I almost made it. I have the following:
Script into example.com/test/websockets.html
`...
<script> const ws = new WebSocket("wss://example.com:4242"); ws.addEventListener('message', (event) => {
console.log("Message from server!" + event.data);
});
</script>
...`
PHP with Workerman in example.com/test/websockets.php
<?php
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
// Create a Websocket server
$ws_worker = new Worker('websocket://example.com:4242');
$ws_worker->count = 4;
$ws_worker->onConnect = function ($connection) {
//$connection->send('message');
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function ($connection, $data) use ($ws_worker) {
// Send hello $data
$connection->send('Hello ' . $data);
// For each client do this
foreach($ws_worker->connections as $clientConnection){
$clientConnection->send($data);
}
};
// Emitted when connection closed
$ws_worker->onClose = function ($connection) {
echo "Connection closed\n";
};
// Run worker
Worker::runAll();
When i run PHP script, and go to exmaple.com/test/websockets.php i get next error in console:
WebSocket connection to 'wss://example.com:4242/' failed: (anonym) @ (index):9
But in script, i see, that i connected and disconnected immediately twice.
So, i found that my server isn't set up to reverse proxy. I also can provide ssl certificates with my script - but i don't want to do it... I tried change my nginx configuration with next lines:
server {
listen 443 http2 ssl;
listen [::]:443 http2 ssl;
location ~ ^/test/(.*$) {
tcp_nodelay on;
keepalive_timeout 1200s 1200s;
keepalive_requests 100000;
proxy_pass http://127.0.0.1:4242/$1;
proxy_read_timeout 1200s;
proxy_send_timeout 1200s;
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;
}
This is wouldn't work for me.
What else do I need to do and configure so that I can run websockets on my server? If possible, with examples Please, if additional information is required, I will provide it. But I want to figure it out and get help