2018-11-20 10:51:00 +00:00
|
|
|
<?php
|
|
|
|
|
|
2018-11-21 11:13:40 +00:00
|
|
|
namespace BeyondCode\LaravelWebSockets\Server;
|
2018-11-20 10:51:00 +00:00
|
|
|
|
|
|
|
|
use Ratchet\Http\Router;
|
2018-11-22 22:55:39 +00:00
|
|
|
use React\Socket\SecureServer;
|
|
|
|
|
use React\Socket\Server;
|
2018-11-20 10:51:00 +00:00
|
|
|
use Ratchet\Http\HttpServer;
|
|
|
|
|
use Ratchet\Server\IoServer;
|
|
|
|
|
use React\EventLoop\LoopInterface;
|
|
|
|
|
use React\EventLoop\Factory as LoopFactory;
|
|
|
|
|
use Symfony\Component\Routing\RequestContext;
|
|
|
|
|
use Symfony\Component\Routing\Matcher\UrlMatcher;
|
2018-11-22 07:49:26 +00:00
|
|
|
use Symfony\Component\Routing\RouteCollection;
|
2018-11-20 10:51:00 +00:00
|
|
|
|
2018-11-21 20:23:25 +00:00
|
|
|
class WebSocketServer
|
|
|
|
|
{
|
2018-11-22 07:49:26 +00:00
|
|
|
/** @var string */
|
|
|
|
|
protected $host = '127.0.0.1';
|
2018-11-20 10:51:00 +00:00
|
|
|
|
2018-11-22 07:49:26 +00:00
|
|
|
/** @var int */
|
|
|
|
|
protected $port = 8080;
|
|
|
|
|
|
|
|
|
|
/** @var \React\EventLoop\LoopInterface */
|
|
|
|
|
protected $loop;
|
|
|
|
|
|
|
|
|
|
/** @var \Symfony\Component\Routing\RouteCollection */
|
|
|
|
|
protected $routes;
|
|
|
|
|
|
|
|
|
|
public function __construct(RouteCollection $routes)
|
|
|
|
|
{
|
|
|
|
|
$this->loop = LoopFactory::create();
|
|
|
|
|
|
|
|
|
|
$this->routes = $routes;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function setHost(string $host)
|
|
|
|
|
{
|
|
|
|
|
$this->host = $host;
|
|
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function setPort(string $port)
|
2018-11-21 20:23:25 +00:00
|
|
|
{
|
2018-11-22 07:49:26 +00:00
|
|
|
$this->port = $port;
|
2018-11-20 10:51:00 +00:00
|
|
|
|
2018-11-22 07:49:26 +00:00
|
|
|
return $this;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function setLoop(LoopInterface $loop)
|
|
|
|
|
{
|
|
|
|
|
$this->loop = $loop;
|
|
|
|
|
|
|
|
|
|
return $this;
|
2018-11-20 10:51:00 +00:00
|
|
|
}
|
|
|
|
|
|
2018-11-21 20:23:25 +00:00
|
|
|
public function run()
|
|
|
|
|
{
|
2018-11-22 07:49:26 +00:00
|
|
|
$server = $this->createServer();
|
|
|
|
|
|
|
|
|
|
$server->run();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function createServer(): IoServer
|
|
|
|
|
{
|
2018-11-22 22:55:39 +00:00
|
|
|
$socket = new Server("{$this->host}:{$this->port}", $this->loop);
|
|
|
|
|
|
|
|
|
|
if (config('websockets.ssl.local_cert')) {
|
|
|
|
|
$socket = new SecureServer($socket, $this->loop, config('websockets.ssl'));
|
|
|
|
|
}
|
2018-11-22 07:49:26 +00:00
|
|
|
|
|
|
|
|
$urlMatcher = new UrlMatcher($this->routes, new RequestContext);
|
|
|
|
|
|
|
|
|
|
$router = new Router($urlMatcher);
|
|
|
|
|
|
|
|
|
|
$httpServer = new HttpServer($router);
|
|
|
|
|
|
|
|
|
|
return new IoServer($httpServer, $socket, $this->loop);
|
2018-11-20 10:51:00 +00:00
|
|
|
}
|
|
|
|
|
}
|