Skip to content

Allow accessing websocket connections via protocol#130

Open
thekid wants to merge 2 commits intomasterfrom
feature/ws-connections-access
Open

Allow accessing websocket connections via protocol#130
thekid wants to merge 2 commits intomasterfrom
feature/ws-connections-access

Conversation

@thekid
Copy link
Copy Markdown
Member

@thekid thekid commented Apr 26, 2026

This allows writing a websocket-based chat, including running it with the development webserver.

use io\redis\RedisProtocol;
use web\Application;
use web\handler\WebSocket;

class Chat extends Application {

  public function initialize($kernel) {
    $redis= new RedisProtocol('redis://localhost');
    $redis->command('SUBSCRIBE', 'chat');

    $kernel->server->select($redis->socket(), function($socket) use($redis, $kernel) {
      $websocket= $kernel->protocol('websocket');
      while (!$socket->eof()) {
        yield 'read' => null;
        [, , $payload]= $redis->receive();
        $input= json_decode($payload, true);
        $output= /* ...shortened for brevity */;
        
        $websocket->broadcast($output, prioritize: [$input['id']]);
      }
    });
  }

  public function routes() {
    $redis= new RedisProtocol('redis://localhost');
    return [
      '/ws' => new WebSocket(function($conn, $payload) use($redis) {
        if ($input= json_decode($payload, true)) {
          $redis->command('PUBLISH', 'chat', json_encode(['id' => $conn->id()] + $input));
        }
      }),
      '/' => function($request, $response) {
        // ...shortened for brevity: output HTML / CSS / JavaScript to connect
      }
    ];
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant