PHP code example of mix / websocket-skeleton

1. Go to this page and download the library: Download mix/websocket-skeleton 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/ */

    

mix / websocket-skeleton example snippets


$vega->handle('/websocket', [new WebSocket(), 'index'])->methods('GET');



namespace App\Controller;

use App\Container\Upgrader;
use App\Service\Session;
use Mix\Vega\Context;

class WebSocket
{

    /**
     * @param Context $ctx
     */
    public function index(Context $ctx)
    {
        $conn = Upgrader::instance()->upgrade($ctx->request, $ctx->response);
        $session = new Session($conn);
        $session->start();
    }

}



namespace App\Service;

use App\Handler\Hello;
use Mix\WebSocket\Connection;
use Swoole\Coroutine\Channel;

class Session
{

    /**
     * @var Connection
     */
    protected $conn;

    /**
     * @var Channel
     */
    protected $writeChan;

    /**
     * Session constructor.
     * @param Connection $conn
     */
    public function __construct(Connection $conn)
    {
        $this->conn = $conn;
        $this->writeChan = new Channel(10);
    }

    /**
     * @param string $data
     */
    public function send(string $data): void
    {
        $this->writeChan->push($data);
    }

    public function start(): void
    {
        // 接收消息
        go(function () {
            while (true) {
                $frame = $this->conn->recv();
                $message = $frame->data;

                (new Hello($this))->index($message);
            }
        });

        // 发送消息
        go(function () {
            while (true) {
                $data = $this->writeChan->pop();
                if (!$data) {
                    return;
                }
                $frame = new \Swoole\WebSocket\Frame();
                $frame->data = $data;
                $frame->opcode = WEBSOCKET_OPCODE_TEXT; // or WEBSOCKET_OPCODE_BINARY
                $this->conn->send($frame);
            }
        });
    }

}
json
"scripts": {
    "swooleco:start": "php bin/swooleco.php",
    "cli:clearcache": "php bin/cli.php clearcache"
}

php bin/swooleco.php start

(new Hello($this))->index($message);

location /websocket {
    proxy_pass http://127.0.0.1:9502;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}