title: PHP Websocket Client - Keep connection open
body: <p>I am using <a href="https://github.com/arthurkushman/php-wss" rel="nofollow noreferrer">PHP-WSS</a> in a laravel application and need to keep a websocket client open to receive various messages from the websocket server.</p>
  <p>So far I built a CLI php script that I can execute and wait for messages to arrive.</p>
  <p>I built the following function to test...</p>
  <p>The question is, to keep the connection open for any messages that might be sent from the server, is it a good approach to do it as below using a while(true) loop? Is there anyway I can do this better? (To me it looks dirty and wish to improve it and do it properly)</p>
  <pre><code>function testWebsocketClient() {
      $url = 'wss://example.com/?token=xyz123456';
      $client = new WebSocketClient($url, new ClientConfig());
      while(true){
          sleep(5);
          $client-&gt;send('test');
          $return = $client-&gt;receive(); // test received OK
      }
      return $return;
  }
  </code></pre>
  <p>UPDATE: Anyone using PHP-WSS I found a bug in Connection.php in broadCast method.</p>
  <p>Original function tries to send on a dead connection, which shows the following error
  Empty read; connection dead?
  (Note the EOF = true)</p>
  <pre><code>public function broadCast(string $data): void
  {
      foreach ($this-&gt;clients as $client) {
          if (is_resource($client) ) { // check if not yet closed/broken etc
              fwrite($client, $this-&gt;encode($data));
          } else {
              echo 'Skipping a closed connection';
          }
      }
  }
  </code></pre>
  <p>I changed it to</p>
  <pre><code>public function broadCast(string $data): void
  {
      foreach ($this-&gt;clients as $client) {
          //echo PHP_EOL. stream_get_status($client) .PHP_EOL;
          $clientMeta = ( stream_get_meta_data($client) );
          $clientEof = $clientMeta['eof'];
          if (is_resource($client) &amp;&amp; $clientEof == false ) { // check if not yet closed/broken etc
              fwrite($client, $this-&gt;encode($data));
          } else {
              echo 'Skipping a closed connection';
          }
      }
  }
  </code></pre>