/** * Create server * - bind to port * - listen port * @throws ListenException * @throws BindException */ function create($blocking = true) { $this->open(); $serverSocket = $this->getSocketResource(); if (!socket_bind($serverSocket, $this->getIp(), $this->getPort())) { throw new BindException($this); } $this->getEventDispatcher()->dispatch(BindEvent::getEventName(), new BindEvent($this, $this)); if (!socket_listen($serverSocket)) { throw new ListenException($this); } if ($blocking) { socket_set_block($serverSocket); } else { socket_set_nonblock($serverSocket); } $this->start(); while ($this->running) { $clientSocket = socket_accept($serverSocket); if (false == $clientSocket) { continue; } $socket = new Socket($this->getAddressType(), $this->getSocketType(), $this->getTransport(), $this->getEventDispatcher()); $socket->setSocketResource($clientSocket); $socket->getEventDispatcher()->dispatch(NewConnectionEvent::getEventName(), new NewConnectionEvent($socket, $this)); } }
<?php require_once __DIR__ . '/../vendor/autoload.php'; use Aysheka\Socket\Client; use Aysheka\Socket\Type; use Symfony\Component\EventDispatcher\EventDispatcher; use Aysheka\Socket\Event\SocketEvent; use Aysheka\Socket\Server\Event\NewConnectionEvent; use Aysheka\Socket\Event\Init\OpenEvent; use Aysheka\Socket\Event\Init\CloseEvent; use Aysheka\Socket\Client\Event\ConnectEvent; use Aysheka\Socket\Server\Event\BindEvent; use Aysheka\Socket\Event\IO\ReadEvent; use Aysheka\Socket\Event\IO\WriteEvent; $eventDispatcher = new EventDispatcher(); $eventDispatcher->addListener(NewConnectionEvent::getEventName(), function (NewConnectionEvent $event) { $socket = $event->getSocket(); $socket->write("HELLO I'm test server\n"); // Read bytes from socket if available while ($read = $socket->read()) { echo "Read data: [{$read}]"; $socket->write('Response'); usleep(50); } }); $eventDispatcher->addListener(OpenEvent::getEventName(), function (OpenEvent $event) { echo "Open\n"; }); $eventDispatcher->addListener(CloseEvent::getEventName(), function (CloseEvent $event) { echo "Close\n"; });