PHP code example of gomoob / php-websocket-server

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

    

gomoob / php-websocket-server example snippets


// PHP Server (in most cases a Web Server) to Web Socket server client, allows to send one message which is forwared to
// several opened WebSocket connections
$phpClient = new WebSocketClient('ws://localhost:8080');
$phpClient->send(WebSocketRequest::create($message, ['language' => 'FR']);



echo "WebSocket server started, enter Ctrl+C to stop server." . PHP_EOL;
\Gomoob\WebSocket\Server\WebSocketServer::factory()->run();

// Open a Server / Server WebSocket connection
$phpClient = new WebSocketClient('ws://localhost:8080');

// Forward a message to all the WebSocket client connections associated to 'tag1' and 'tag2'
$response = $phpClient->send(
    WebSocketRequest::create(
        $message, 
        [
            'tag1' => 'tag1Value',
            'tag2' => 'tag2Value'
        ]
    )
);

// Somewhere in our code we use a \Gomoob\WebSocket\IWebSocketClient ...
// We suppose this code is implemented in MyPowerfulService->serviceMethod();
$phpClient->send(WebSocketRequest::create('Message 0.')->setTags(['tag0' => 'tag0Value']));
$phpClient->send(WebSocketRequest::create('Message 1.')->setTags(['tag1' => 'tag0Value']));
$phpClient->send(WebSocketRequest::create('Message 2.')->setTags(['tag0' => 'tag0Value', 'tag1' => 'tag1Value']));
		
// Then we write a test case by replacing the real WebSocket client implementation with the mock one
class SampleTestCase extends TestCase
{
    public function setUp() {
        $this->webSocketClient = new WebSocketClientMock();
        $this->myPowerfulService->setWebSocketClient($this->webSocketClient);
    }

    public function testServiceMethod() {
    
        // Calls the method to test
        $this->myPowerfulService->serviceMethod();
    
        // Checks the right requests were sent
        $webSocketRequests = $this->webSocketClient->findByTags(['tag0' => 'tag0Value']);
		$this->assertCount(2, $webSocketRequests);
		$this->assertContains($webSocketRequest0, $webSocketRequests);
		$this->assertNotContains($webSocketRequest1, $webSocketRequests);
		$this->assertContains($webSocketRequest2, $webSocketRequests);
    }
}

class MyMessage {
    private $messageProperty1;
    public function __construct($messageProperty1) {
        $this->messageProperty1 = $messageProperty1; 
    }
    public function getMessageProperty1() {
        return $this->messageProperty1;
    }
}

WebSocketClient::factory('ws://localhost:8080')->send(WebSocketRequest::create(new MyMessage('Hello !')));

class MyMessage implements \JsonSerializable {
   ...
   public function jsonSerialize() {
       return [
           'messageProperty1' => $this->messageProperty1;
        ];
   }
}

use Gomoob\WebSocket\IMessageParser;

class MyMessageParser implement IMessageParser {
    public function parse(array $arrayMessage)
    {
        // Ensure the array contains only valid key names
        foreach (array_keys($arrayMessage) as $key) {
            if (!is_string($key) || !in_array($key, ['messageProperty1'])) {
                throw new \InvalidArgumentException('Unexpected property \'' . $key . '\' !');
            }
        }
        
        // The 'messageProperty1' property is mandatory
        if (!array_key_exists('messageProperty1', $arrayMessage)) {
            throw new \InvalidArgumentException('No \'messageProperty1\' property found !');
        }
        
        return new MyMessage($arrayMessage['messageProperty1']);
    }
}

WebSocketServer::factory(
    [
    	'messageParser' => new MyMessageParser()
    ]
)->run();

/**
 * Interface which defines an authorization manager. An authorization manager allows to control authorization while
 * opening Web Socket connections and sending messages over Web Sockets.
 *
 * @author Baptiste Gaillard ([email protected])
 */
interface IAuthManager
{
    /**
     * Function used to indicate if connection opening is authorized.
     *
     * @param \Ratchet\ConnectionInterface $connection the current Ratchet connection.
     *
     * @return boolean `true` if the connection opening is authorized, `false` otherwise.
     */
    public function authorizeOpen(ConnectionInterface $connection);

    /**
     * Function used to indicate if message sending is authorized.
     *
     * @param \Ratchet\ConnectionInterface $connection the current Ratchet connection.
     * @param \Gomoob\WebSocket\IWebSocketRequest $webSocketRequest the current Gomoob WebSocket request.
     */
    public function authorizeSend(ConnectionInterface $connection, IWebSocketRequest $webSocketRequest);
}

WebSocketServer::factory(
    [
    	'authManager' => ApplicationsAuthManager::factory(
    	    [
    	        'authorizeOpen' => false,
    	    	'configurationFile' => __DIR__ . '/auth.yml'
    	    ]
    	)
    ]
)->run();

WebSocketClient::factory('ws://localhost:8080')->send(
    WebSocketRequest::create(
        new MyMessage('Hello !')
    )->setMetadata(
        [
            'key' => 'application2',
            'secret' => '33yLWdynhaqm9tYjDFKf8gB8zmAPKdDP'
        ]
    )
);