PHP code example of nailfor / php-websocket-client

1. Go to this page and download the library: Download nailfor/php-websocket-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nailfor / php-websocket-client example snippets



use nailfor\websocket\ClientFactory;

class WebSocketTest
{
    public function receiveMsg($reason)
    {
        echo "RECEIVE:";
        print_r($reason->getMessage());
    }

    public function afterConnect($reason)
    {
        $data = [
            "somedata" => "peesdata",
        ];
        //'topic' is a TOPIC_NAME from options
        ClientFactory::$client->publish('topic', $data);
    }

    public function errorMsg($reason)
    {
        echo $reason->getMessage(). PHP_EOL;
        exit;
    }
    
    public function closeMsg()
    {
        echo "closed!!!!". PHP_EOL;
        exit;
    }
    
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $options = [
            'topics' => [
                //TOPIC_NAME => events[]
                'topic' => [
                    'events' => [
                        //EVENT_NAME=>function 
                        'PUBLISH_RECEIVED'  => [$this, 'receiveMsg'],
                    ],
                ],
            ],
            'connect'   => [$this, 'afterConnect'],
            'timeout'   => [$this, 'errorMsg'],
            'error'     => [$this, 'errorMsg'],
            'close'     => [$this, 'closeMsg'],
        ];

        ClientFactory::run('ws://127.0.0.1:8080', $options);
    }
}