Author: Chris
Inheritance: extends Evenement\EventEmitter
 public function __construct(WebSocketServer $server, array $allowedOrigins)
 {
     $server->on("handshake", function (Handshake $handshake) use($allowedOrigins) {
         $originHeader = $handshake->getRequest()->getHeader('Origin', null);
         $origin = $originHeader ? $originHeader->getFieldValue() : null;
         if (in_array("*", $allowedOrigins) || !in_array($origin, $allowedOrigins)) {
             $handshake->abort();
         } else {
             // Confirm that the origin is allowed
             $handshake->getResponse()->getHeaders()->addHeaderLine("Access-Control-Allow-Origin", $origin);
         }
     });
 }
Esempio n. 2
0
 public function launch()
 {
     $server = new WebSocketServer($this->config['url'], $this->loop, $this->logger);
     $this->loop->addPeriodicTimer($this->config['delay_try_reconnect'], function () {
         $timer = 0;
         foreach ($this->bots_retrying as $tb_id => $true) {
             $this->loop->addTimer($timer++, function () use($tb_id) {
                 $this->logger->debug('Try to reconnect client for bot ' . $tb_id);
                 $this->addSlackClient($this->bots[$tb_id]);
             });
         }
     });
     $this->loop->addPeriodicTimer($this->config['delay_ping'], function () {
         foreach ($this->bots_connected as $tb_id => $connected) {
             if ($connected) {
                 $always_connected = $this->bots[$tb_id]->clientSendPing();
                 if (!$always_connected) {
                     $this->logger->warn('Ping fail set to retry for bot ' . $tb_id);
                     $this->setToRetry($this->bots[$tb_id]);
                 }
             }
         }
     });
     $server->on('message', function (WebSocketTransportInterface $user, WebSocketMessage $message) {
         $data = json_decode($message->getData(), true);
         $this->logger->debug("Bot2hook websocket server receive message " . $message->getData());
         if (is_array($data) && isset($data['type'])) {
             switch ($data['type']) {
                 case 'add_bot':
                     $this->logger->debug("New bot receive via incomming webhook " . json_encode($data['bot']));
                     $bot = new Bot($data['bot']);
                     $this->addSlackClient($bot);
                     break;
                 case 'status':
                     $user->sendString(json_encode(['bot2hook' => ['bots' => $this->bots, 'bots_connected' => $this->bots_connected, 'bots_retrying' => $this->bots_retrying]]));
                     break;
                 case 'reporting':
                     $user->sendString(json_encode(['memory' => ['usage' => memory_get_usage(true), 'peak_usage' => memory_get_peak_usage(true), 'limit' => $this->getMemoryLimit()], 'bots_count' => ['connected' => count($this->bots_connected), 'retrying' => count($this->bots_retrying)]]));
                     break;
             }
         }
     });
     $server->bind();
     $this->init();
     $this->loop->run();
 }
Esempio n. 3
0
 * Date: 27-11-13
 * Time: 18:00
 */
require_once "../vendor/autoload.php";
// Run from command prompt > php demo.php
use Devristo\Phpws\RemoteEvent\RemoteEventTransport;
use Devristo\Phpws\Protocol\StackTransport;
use Devristo\Phpws\Protocol\TransportInterface;
use Devristo\Phpws\Server\WebSocketServer;
$loop = \React\EventLoop\Factory::create();
// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
// Create a WebSocket server and create a router which sends all user requesting /echo to the DemoEchoHandler above
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);
$handler = new \Devristo\Phpws\RemoteEvent\RemoteEvents($logger);
$server->on("connect", function (TransportInterface $transport) use($loop, $logger, $handler) {
    $stack = StackTransport::create($transport, array(function (TransportInterface $transport) use($loop, $logger) {
        return new RemoteEventTransport($transport, $loop, $logger);
    }));
    $handler->listenTo($stack);
});
$handler->room("time")->on("subscribe", function (StackTransport $transport) use($logger, $handler) {
    $logger->notice("Someone joined our room full of time enthousiasts!!");
});
// Each 0.5 seconds sent the time to all connected clients
$loop->addPeriodicTimer(0.5, function () use($server, $handler, $logger) {
    $time = new DateTime();
    $string = $time->format("Y-m-d H:i:s");
    if (count($handler->room("time")->getMembers())) {
Esempio n. 4
0
#!/php -q
<?php 
require_once "../vendor/autoload.php";
use Devristo\Phpws\Protocol\Handshake;
use Devristo\Phpws\Protocol\TransportInterface;
use Devristo\Phpws\Protocol\WebSocketTransport;
use Devristo\Phpws\Server\WebSocketServer;
$loop = \React\EventLoop\Factory::create();
// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
// Create a WebSocket server using SSL
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);
$server->on("handshake", function (WebSocketTransport $client, Handshake $handshake) {
    // Here we can alter or abort PHPWS's response to the user
    $handshake->getResponse()->getHeaders()->addHeaderLine("X-WebSocket-Server", "phpws");
    // We can also see which headers the client sent in its handshake. Lets proof it
    $userAgent = $handshake->getRequest()->getHeader('User-Agent')->getFieldValue();
    $handshake->getResponse()->getHeaders()->addHeaderLine("X-User-Agent", $userAgent);
    // Since we cannot see in the browser what headers were sent by the server, we will send them again as a message
    $client->on("connect", function () use($client) {
        // The request and the response is available on the transport object as well.
        $client->sendString($client->getHandshakeResponse()->toString());
    });
});
// Bind the server
$server->bind();
// Start the event loop
$loop->run();
Esempio n. 5
0
         */
        $logger = $this->logger;
        $loop = $this->loop;
        $stackTransport = StackTransport::create($transport, array(function (TransportInterface $carrier) use($loop, $logger) {
            return new RemoteEventTransport($carrier, $loop, $logger);
        }));
        $jsonTransport = $stackTransport->getTopTransport();
        $server = $transport->getHandshakeResponse()->getHeaders()->get('X-WebSocket-Server')->getFieldValue();
        $greetingMessage = RemoteEventMessage::create(null, "greeting", "hello world from {$server}!");
        $jsonTransport->whenResponseTo($greetingMessage, 0.1)->then(function (RemoteEventMessage $result) use($logger, $server) {
            $logger->notice(sprintf("Got '%s' in response to 'hello world from {$server}!'", $result->getData()));
        });
        $jsonTransport->remoteEvent()->on("greeting", function (RemoteEventMessage $message) use($transport, $logger) {
            $logger->notice(sprintf("We got a greeting event from {$transport->getId()}"));
        });
    }
}
$loop = \React\EventLoop\Factory::create();
// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new \Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);
$server->bind();
$server->on("handshake", function (\Devristo\Phpws\Protocol\WebSocketTransportInterface $transport, \Devristo\Phpws\Protocol\Handshake $handshake) {
    $handshake->getResponse()->getHeaders()->addHeaderLine("X-WebSocket-Server", "phpws");
});
$router = new \Devristo\Phpws\Server\UriHandler\ClientRouter($server, $logger);
$router->addRoute('#^/stack#i', new StackHandler($loop, $logger));
// Start the event loop
$loop->run();
Esempio n. 6
0
    protected function getStream(WebSocketTransportInterface $user, $id)
    {
        $userStreams = $this->getStreamsByUser($user);
        return array_key_exists($id, $userStreams) ? $userStreams[$id] : null;
    }
    /**
     * @param WebSocketTransportInterface $user
     * @return \React\Stream\Stream[]
     */
    protected function getStreamsByUser(WebSocketTransportInterface $user)
    {
        return array_key_exists($user->getId(), $this->streams) ? $this->streams[$user->getId()] : array();
    }
    protected function removeStream(WebSocketTransportInterface $user, $id)
    {
        unset($this->streams[$user->getId()][$id]);
    }
    protected function addStream(WebSocketTransportInterface $user, $id, \React\Stream\Stream $stream)
    {
        $this->streams[$user->getId()][$id] = $stream;
    }
}
$loop = \React\EventLoop\Factory::create();
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);
$router = new \Devristo\Phpws\Server\UriHandler\ClientRouter($server, $logger);
$router->addRoute("#^/proxy\$#i", new ProxyHandler($loop, $logger));
$server->bind();
$loop->run();
Esempio n. 7
0
#!/php -q
<?php 
require_once "../vendor/autoload.php";
use Devristo\Phpws\Messaging\WebSocketMessageInterface;
use Devristo\Phpws\Protocol\WebSocketTransportInterface;
use Devristo\Phpws\Server\WebSocketServer;
$loop = \React\EventLoop\Factory::create();
// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
// Create a WebSocket server using SSL
$server = new WebSocketServer("ssl://0.0.0.0:12345", $loop, $logger);
$context = stream_context_create();
stream_context_set_option($context, 'ssl', 'local_cert', "democert.pem");
stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
$server->setStreamContext($context);
// Sent a welcome message when a client connects
$server->on("connect", function (WebSocketTransportInterface $user) {
    $user->sendString("Hey! I am the echo robot. I will repeat all your input!");
});
// Echo back any message the user sends
$server->on("message", function (WebSocketTransportInterface $user, WebSocketMessageInterface $message) use($logger) {
    $logger->notice(sprintf("We have got '%s' from client %s", $message->getData(), $user->getId()));
    $user->sendString($message->getData());
});
// Bind the server
$server->bind();
// Start the event loop
$loop->run();
Esempio n. 8
0
#!/php -q
<?php 
require_once "../vendor/autoload.php";
use Devristo\Phpws\Server\WebSocketServer;
$loop = \React\EventLoop\Factory::create();
// Create a logger which writes everything to the STDOUT
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
// Create a WebSocket server using SSL
$server = new WebSocketServer("tcp://0.0.0.0:12345", $loop, $logger);
// Each 0.5 seconds sent the time to all connected clients
$loop->addPeriodicTimer(0.5, function () use($server, $logger) {
    $time = new DateTime();
    $string = $time->format("Y-m-d H:i:s");
    $logger->notice("Broadcasting time to all clients: {$string}");
    foreach ($server->getConnections() as $client) {
        $client->sendString($string);
    }
});
// Bind the server
$server->bind();
// Start the event loop
$loop->run();