Saturday, September 5, 2020

Create Secure Web Socket (WSS) with Ratchet PHP


Recently I was working on PHP project where we I was create secure web socket which is accessible with wss:// protocol. For this I struggled for couple of hours so here in blog I am going to explain how to do that so it can save your time. 

Earlier version was not supporting WSS but later it introduced React socket server which allows SSL connection. So here are steps you need to follow. 

First add all the required classed in your php file.

use Ratchet\Server\IoServer;

use Ratchet\Http\HttpServer;

use Ratchet\WebSocket\WsServer;

use MyApp\Socket;

In above example Socket is my class file which has all listeners. After this add auto load file.

require dirname( __FILE__ ) . '/vendor/autoload.php';

Next we will create our socket app. 

$app = new \Ratchet\Http\HttpServer(
    new \Ratchet\WebSocket\WsServer(
        new \MyApp\Socket()

Now next step is to create React Secure server.

$loop = \React\EventLoop\Factory::create();
$webSock = new \React\Socket\Server('', $loop);

We are using  so this socket can be connected from anywhere. 

Now lets create secure server by adding path to certificate and key

$webSock = new \React\Socket\SecureServer($webSock, $loop, [
    'local_cert' => 'CRT_PATH', 
    'local_pk'=> 'KEY_PATH', 
    'allow_self_signed' => true, 
    'verify_peer' => false

Now finally we will run our server.

$webSock = new \Ratchet\Server\IoServer($app, $webSock, $loop);

That's it. It will start your server to which you can connect with WSS protocol. To test you can use WebSocket ECHO test.

Hope this helps you.

No comments:

Post a Comment