PHP code example of lexty / websocketserver

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

    

lexty / websocketserver example snippets




use Lexty\WebSocketServer\Server;
use Lexty\WebSocketServer\BaseApplication;

// Make sure composer dependencies have been installed
  public function __construct()
    {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn, HandlerInterface $handler)
    {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $from, PayloadInterface $msg, HandlerInterface $handler)
    {
        if (!$msg->checkEncoding('utf-8')) {
            return;
        }
        $message = 'user #' . $from->id . ' (' . $handler->pid . '): ' . strip_tags($msg);

        foreach ($this->clients as $client) {
            $client->send($message);
        }
    }

    public function onClose(ConnectionInterface $conn = null, HandlerInterface $handler)
    {
        $this->clients->detach($conn);
    }
}

$server = new Server('0.0.0.0', 8080, '/tmp/web-socket-server.pid');
$server
    ->registerApplication('/chat', new Chat)
    ->run();



use Lexty\WebSocketServer\BaseApplication;

class App extends BaseApplication 
{
    public function onOpen(ConnectionInterface $conn, HandlerInterface $handler)
    {
        $user = $conn->request->query['user'];
        $auth = $conn->request->query['auth'];
        if (!$user || !$auth) { // some authorization
            $conn->close();
        }
    }
}


use Symfony\Component\DependencyInjection\ContainerBuilder;
use Lexty\WebSocketServer\Applications\Chat;

$container = new ContainerBuilder;
// MyConnectionClass must implements ConnectionInterface
$container->setParameter('lexty.websocketserver.payload.class', 'MyConnectionClass');
// MyPayloadClass must implements PayloadInterface
$container->setParameter('lexty.websocketserver.connection.class', 'MyPayloadClass');

$server = new Server('localhost', 8080, '/tmp/websocketserver.pid', 1, $container)
    ->registerApplication('/chat', new Chat)
    ->run();