Search code examples
phpsslwebsocketratchet

php ratchet websocket SSL connect?


I have a ratchet chat server file

use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use MyAppChat\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
    new WsServer(
        new Chat()
    )
  , 26666
);
$server->run();

I using Websocket to connect with ws and it works fine

if ("WebSocket" in window) {
    var ws = new WebSocket("ws://ratchet.mydomain.org:8888");
    ws.onopen = function() {
        // Web Socket is connected. You can send data by send() method.
        ws.send("message to send");
    };
    ws.onmessage = function (evt) { 
        var received_msg = evt.data;
    };
    ws.onclose = function() { 
        // websocket is closed. 
    };
} else {
  // the browser doesn't support WebSocket.
}

I want secure connection, so I try to connect with SSL but is not work.

if ("WebSocket" in window) {
    var ws = new WebSocket("wss://ratchet.mydomain.org:8888");
    ws.onopen = function() {
        // Web Socket is connected. You can send data by send() method.
        ws.send("message to send");
    };
    ws.onmessage = function (evt) { 
        var received_msg = evt.data;
    };
    ws.onclose = function() { 
        // websocket is closed. 
    };
} else {
  // the browser doesn't support WebSocket.
}

My question is how to connect websocket with SSL connection

Any idea?


Solution

  • If you are using Apache web server (2.4 or above), enable these modules in httpd.conf file :

    1. mod_proxy.so
    2. mod_proxy_wstunnel.so

    Add this setting to your httpd.conf file

    ProxyPass /wss2/ ws://ratchet.mydomain.org:8888/
    

    Use this URL in your JavaScript call when you want a WSS connection:

    var ws = new WebSocket("wss://ratchet.mydomain.org/wss2/NNN");
    

    Restart Apache web server and make sure that your Ratchet worker (web socket connection) is open before applying the settings (telnet hostname port).