Example #1
0
 public function onConnectedEvent($connSocket, $events, $arg)
 {
     $connId = $arg[0];
     Debug::netEvent(get_class($this) . '::' . __METHOD__ . '(' . $connId . ') invoked. ');
     //处理两种状态,一种是直接连接成功,一种是异步通知
     if (isset($this->checkConnEvPool[$connId])) {
         // 异步通知
         // 因为 注册 EV_WRITE 事件是非持久模式的,所以这里不用 delete, 只需要 unset pool 即可
         unset($this->checkConnSocketPool[$connId]);
         unset($this->checkConnEvPool[$connId]);
     }
     $evBuf = event_buffer_new($connSocket, array($this, 'onEvBufReadEvent'), array($this, 'onEvBufWriteEvent'), array($this, 'onEventEvent'), array($connId));
     event_buffer_base_set($evBuf, daemon::$eventBase);
     event_buffer_priority_set($evBuf, 10);
     event_buffer_watermark_set($evBuf, EV_READ, $this->evBufLowMark, $this->evBufHighMark);
     if (!event_buffer_enable($evBuf, EV_READ | EV_WRITE | EV_PERSIST)) {
         Debug::netErrorEvent(get_class($this) . '::' . __METHOD__ . ': can not set base of buffer. #' . $connId);
         //            socket_close($connSocket);
         fclose($connSocket);
         return;
     }
     // 调试这里时,浪费了很多时间,必须注意的是,以上 event 所用的变量如果在函数中,如果没有交给其他的变量引用,在函数结束时就会销毁,
     // 造成连接直接断或者bufferevent 不能触发。晕啊晕。
     $this->connSocketPool[$connId] = $connSocket;
     $this->connEvBufPool[$connId] = $evBuf;
     list($ip, $port) = explode(':', stream_socket_get_name($connSocket, true));
     $this->updateLastContact($connId);
     $this->onConnected($connId, $ip, $port);
 }
Example #2
0
 /**
  * Sets up the stream connection
  *
  * @throws PhpAmqpLib_Exception_AMQPRuntimeException
  * @throws Exception
  */
 public function connect()
 {
     $errstr = $errno = null;
     $remote = sprintf('%s://%s:%s', $this->protocol, $this->host, $this->port);
     set_error_handler(array($this, 'error_handler'));
     $this->sock = stream_socket_client($remote, $errno, $errstr, $this->connection_timeout, STREAM_CLIENT_CONNECT, $this->context);
     restore_error_handler();
     if (false === $this->sock) {
         throw new PhpAmqpLib_Exception_AMQPRuntimeException(sprintf('Error Connecting to server(%s): %s ', $errno, $errstr), $errno);
     }
     if (false === stream_socket_get_name($this->sock, true)) {
         throw new PhpAmqpLib_Exception_AMQPRuntimeException(sprintf('Connection refused: %s ', $remote));
     }
     list($sec, $uSec) = PhpAmqpLib_Helper_MiscHelper::splitSecondsMicroseconds($this->read_write_timeout);
     if (!stream_set_timeout($this->sock, $sec, $uSec)) {
         throw new PhpAmqpLib_Exception_AMQPIOException('Timeout could not be set');
     }
     // php cannot capture signals while streams are blocking
     if ($this->canDispatchPcntlSignal) {
         stream_set_blocking($this->sock, 0);
         stream_set_write_buffer($this->sock, 0);
         if (function_exists('stream_set_read_buffer')) {
             stream_set_read_buffer($this->sock, 0);
         }
     } else {
         stream_set_blocking($this->sock, 1);
     }
     if ($this->keepalive) {
         $this->enable_keepalive();
     }
 }
 protected function onMessage($connectionId, $data, $type)
 {
     //вызывается при получении сообщения от клиента
     if (!strlen($data)) {
         return;
     }
     //антифлуд:
     $source = explode(':', stream_socket_get_name($this->clients[$connectionId], true));
     $ip = $source[0];
     $time = time();
     if (isset($this->ips[$ip]) && $this->ips[$ip] == $time) {
         return;
     } else {
         $this->ips[$ip] = $time;
     }
     if ($login = array_search($connectionId, $this->logins)) {
         $message = $login . ': ' . strip_tags($data);
         $this->sendPacketToMaster('message', $message);
         $this->sendPacketToClients('message', $message);
     } else {
         if (preg_match('/^[a-zA-Z0-9]{1,10}$/', $data, $match)) {
             if (isset($this->logins[$match[0]])) {
                 $this->sendPacketToClient($connectionId, 'message', 'Система: выбранное вами имя занято, попробуйте другое.');
             } else {
                 $this->logins[$match[0]] = -1;
                 $this->sendPacketToMaster('login', array('login' => $match[0], 'clientId' => $connectionId));
             }
         } else {
             $this->sendPacketToClient($connectionId, 'message', 'Система: ошибка при выборе имени. В имени можно использовать английские буквы и цифры. Имя не должно превышать 10 символов.');
         }
     }
     //var_export($data);
     //шлем всем сообщение, о том, что пишет один из клиентов
     //echo $data . "\n";
 }
 public function loop()
 {
     $this->in_loop = true;
     while ($this->in_loop) {
         $conn = false;
         $read = array($this->socket);
         $write = null;
         $except = null;
         declare (ticks=1) {
             // stream_socket_accept() doesn't block on some(?) of the ARM systems
             // so, wrapping it into stream_select() which works always
             // see https://bugs.php.net/bug.php?id=62816
             if (1 === @stream_select($read, $write, $except, null)) {
                 $conn = @stream_socket_accept($this->socket, 0);
             }
         }
         if (false !== $conn) {
             $remote_addr = stream_socket_get_name($conn, true);
             if (false === $remote_addr) {
                 $remote_addr = null;
             }
             call_user_func($this->callback, $conn, $remote_addr);
         }
         pcntl_signal_dispatch();
     }
 }
Example #5
0
 public function getRemoteAddress()
 {
     if ($this->socket !== false) {
         return stream_socket_get_name($this->socket, true);
     }
     return null;
 }
Example #6
0
 public function onAcceptEvent($bindSocket, $events, $arg)
 {
     $bindSocketId = $arg[0];
     Debug::netEvent(get_class($this) . '::' . __METHOD__ . '(' . $bindSocketId . ') invoked.');
     // add to accept next event
     // why not use EV_PERSIST
     event_add($this->bindSocketEvPool[$bindSocketId]);
     $connSocket = stream_socket_accept($this->bindSocketPool[$bindSocketId]);
     if (!$connSocket) {
         Debug::netErrorEvent(get_class($this) . ': can not accept new TCP-socket');
         return;
     }
     stream_set_blocking($connSocket, 0);
     list($ip, $port) = explode(':', stream_socket_get_name($connSocket, true));
     $connId = daemon::getNextConnId();
     $evBuf = event_buffer_new($connSocket, array($this, 'onEvBufReadEvent'), array($this, 'onEvBufWriteEvent'), array($this, 'onEventEvent'), array($connId));
     event_buffer_base_set($evBuf, daemon::$eventBase);
     event_buffer_priority_set($evBuf, 10);
     event_buffer_watermark_set($evBuf, EV_READ, $this->evBufLowMark, $this->evBufHighMark);
     if (!event_buffer_enable($evBuf, EV_READ | EV_WRITE | EV_PERSIST)) {
         Debug::netErrorEvent(get_class($this) . '::' . __METHOD__ . ': can not set base of buffer. #' . $connId);
         //close socket
         stream_socket_shutdown($connSocket, STREAM_SHUT_RDWR);
         fclose($connSocket);
         return;
     }
     // 调试这里时,浪费了很多时间,必须注意的是,以上 event 所用的变量如果在函数中,如果没有交给其他的变量引用,在函数结束时就会销毁,
     // 造成连接直接断或者bufferevent 不能触发。晕啊晕。
     $this->connSocketPool[$connId] = $connSocket;
     $this->connEvBufPool[$connId] = $evBuf;
     $this->updateLastContact($connId);
     $this->onAccepted($connId, $ip, $port);
 }
function handshake($connect)
{
    //Функция рукопожатия
    $info = array();
    $line = fgets($connect);
    $header = explode(' ', $line);
    $info['method'] = $header[0];
    $info['uri'] = $header[1];
    //считываем заголовки из соединения
    while ($line = rtrim(fgets($connect))) {
        if (preg_match('/\\A(\\S+): (.*)\\z/', $line, $matches)) {
            $info[$matches[1]] = $matches[2];
        } else {
            break;
        }
    }
    $address = explode(':', stream_socket_get_name($connect, true));
    //получаем адрес клиента
    $info['ip'] = $address[0];
    $info['port'] = $address[1];
    if (empty($info['Sec-WebSocket-Key'])) {
        return false;
    }
    //отправляем заголовок согласно протоколу вебсокета
    $SecWebSocketAccept = base64_encode(pack('H*', sha1($info['Sec-WebSocket-Key'] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "Sec-WebSocket-Accept:" . $SecWebSocketAccept . "\r\n\r\n";
    fwrite($connect, $upgrade);
    return $info;
}
Example #8
0
 /** @internal */
 public function checkConnectedSocket($socket)
 {
     // The following hack looks like the only way to
     // detect connection refused errors with PHP's stream sockets.
     if (false === stream_socket_get_name($socket, true)) {
         return Promise\reject(new ConnectionException('Connection refused'));
     }
     return Promise\resolve($socket);
 }
Example #9
0
 function __construct($sock, $ssl = false)
 {
     $this->socket = $sock;
     $this->ssl = $ssl;
     $ip = stream_socket_get_name($this->socket, true);
     $c = strrpos($ip, ":");
     $this->ip = substr($ip, 0, $c);
     $this->lastping = $this->lastpong = time();
 }
Example #10
0
 public function __construct($client)
 {
     if (!is_resource($client)) {
         return;
     }
     $this->_socket = $client;
     $this->name = stream_socket_get_name($client, TRUE);
     $this->initialized = TRUE;
 }
Example #11
0
 public function checkConnectedSocket($socket) : PromiseInterface
 {
     // The following hack looks like the only way to
     // detect connection refused errors with PHP's stream sockets.
     if (false === stream_socket_get_name($socket, true)) {
         return new RejectedPromise(new ConnectionException('Connection refused'));
     }
     return new FulfilledPromise($socket);
 }
 public function __construct(EventHttpServer $Server, $Socket)
 {
     $this->Config = $Server->getConfig();
     $this->BaseEvent = $Server->getBaseEvent();
     $this->Socket = $Socket;
     $this->Name = stream_socket_get_name($Socket, true);
     $this->Expire = time() + $this->Config['ClientTransTimeout'];
     $this->Server = $Server;
     $this->InitSocket();
 }
Example #13
0
 public function __construct(ServerManager $manager, $identifier, $socket)
 {
     $this->manager = $manager;
     $this->identifier = $identifier;
     $this->socket = $socket;
     $addr = stream_socket_get_name($this->socket, true);
     $final = strrpos($addr, ":");
     $this->port = (int) substr($addr, $final + 1);
     $this->address = substr($addr, 0, $final);
 }
Example #14
0
 function read_requests($client, $options = [])
 {
     $options['server'] = stream_socket_get_name($client, true);
     $dt = CY_Util_Stream::http_read($client, $options);
     if ($dt['errno'] !== 0) {
         return $dt;
     }
     if (empty($dt['data'])) {
         return array('errno' => CYE_DATA_EMPTY);
     }
     $o = new http\Message($dt['data']);
     $this->version = $o->getHttpVersion();
     $this->method = $o->getRequestMethod();
     $headers = $o->getHeaders();
     if (!empty($headers['Content-Length'])) {
         if (isset($headers['Expect'])) {
             return array('errno' => CYE_EXPECT_FAIL);
         }
         if (empty($o->getBody())) {
             mp_log(CYE_ERROR, "Bad req:" . $options['server'] . " " . str_replace("\r\n", "\\r\\n", $dt['data']));
         }
     }
     $this->keepalive = isset($headers['Connection']) && strcasecmp($headers['Connection'], 'keep-alive') == 0;
     $this->compress = isset($headers['Accept-Encoding']) && strpos($headers['Accept-Encoding'], 'gzip') !== false;
     if (empty($headers['Host'])) {
         return array('errno' => CYE_ACCESS_DENIED);
     }
     $parts = parse_url('http://' . $headers['Host'] . $o->getRequestUrl());
     $_SERVER['REQUEST_URI'] = $o->getRequestUrl();
     $_SERVER['QUERY_STRING'] = '';
     if (!empty($parts['query'])) {
         $_SERVER['QUERY_STRING'] = $query = $parts['query'];
         parse_str($query, $_GET);
     }
     if (!empty($o->getBody())) {
         if (isset($headers['Content-Type']) && strpos($headers['Content-Type'], 'multipart/form-data') !== false) {
             // grab multipart boundary from content type header
             preg_match('/boundary=(.*)$/', $headers['Content-Type'], $matches);
             // content type is probably regular form-encoded
             if (count($matches)) {
                 $boundary = $matches[1];
                 $_POST = cy_parse_http_multipart($o->getBody(), $boundary);
             }
         }
         if (!isset($boundary)) {
             parse_str($o->getBody(), $_POST);
         }
     }
     if (isset($headers['Cookie'])) {
         $c = new http\Cookie($headers['Cookie']);
         $_COOKIE = $c->getCookies();
     }
     $_REQUEST = array_merge($_GET, $_POST, $_COOKIE);
     return array('errno' => 0);
 }
Example #15
0
 /**
  * Returns local endpoint
  *
  * @return  peer.SocketEndpoint
  * @throws  peer.SocketException
  */
 public function localEndpoint()
 {
     if (is_resource($this->_sock)) {
         if (false === ($addr = stream_socket_get_name($this->_sock, false))) {
             throw new SocketException('Cannot get socket name on ' . $this->_sock);
         }
         return SocketEndpoint::valueOf($addr);
     }
     return null;
     // Not connected
 }
Example #16
0
 /**
  * @param $socket
  * @param ObserverInterface $observer
  */
 public function onConnected($socket, $observer)
 {
     $this->loop->removeWriteStream($socket);
     if (false === stream_socket_get_name($socket, true)) {
         $observer->onError(new ConnectionException('Connection refused'));
         $observer->onCompleted();
         return;
     }
     $observer->onNext(new ConnectorEvent("/connector/connected", new Stream($socket, $this->loop), $this->labels));
     //$observer->onCompleted();
 }
 public function onEventAccept($socket, $event)
 {
     $conn = $this->acceptSocket();
     $remote_addr = stream_socket_get_name($conn, true);
     if (false === $remote_addr) {
         $remote_addr = null;
     }
     self::log('Socket', 'callback');
     call_user_func($this->callback, $conn, $remote_addr);
     pcntl_signal_dispatch();
 }
Example #18
0
 public function __construct($server, $socket)
 {
     $this->server = $server;
     $this->socket = $socket;
     // set some client-information:
     $socketName = stream_socket_get_name($socket, true);
     $tmp = explode(':', $socketName);
     $this->ip = $tmp[0];
     $this->port = $tmp[1];
     $this->connectionId = md5($this->ip . $this->port . spl_object_hash($this));
     $this->log('Connected');
 }
 public function setUp()
 {
     $host = "127.0.0.1";
     $this->serverSocket = stream_socket_server("udp://{$host}:0", $errNo, $errMsg, $flags = STREAM_SERVER_BIND);
     if (!$this->serverSocket) {
         throw new \RuntimeException("Failed to create test-server-socket");
     }
     // get random port
     $socketName = stream_socket_get_name($this->serverSocket, $peerName = false);
     list(, $port) = explode(":", $socketName);
     $this->socketClient = new StreamSocketClient('udp', $host, $port);
 }
Example #20
0
 public function getPeerName(&$ip, &$port)
 {
     $ip = 'N/A';
     $port = -1;
     $name = stream_socket_get_name($this->getHandle(), true);
     $pos = strpos($name, ':');
     if ($pos === false) {
         $ip = $name;
     } else {
         $ip = substr($name, 0, $pos);
         $port = substr($name, $pos + 1);
     }
 }
Example #21
0
 function __construct($socket)
 {
     $this->socket = $socket;
     $this->content_stream = fopen("data://text/plain,", 'r+b');
     $remote_name = stream_socket_get_name($socket, true);
     if ($remote_name) {
         $port_pos = strrpos($remote_name, ":");
         if ($port_pos) {
             $this->remote_addr = substr($remote_name, 0, $port_pos);
         } else {
             $this->remote_addr = $remote_name;
         }
     }
 }
Example #22
0
 public function getPeerName(&$ip, &$port)
 {
     $ip = 'N/A';
     $port = -1;
     $name = stream_socket_get_name($this->getHandle(), true);
     $pos = strpos($name, ':');
     if ($pos === false) {
         $ip = $name;
     } else {
         $ip = substr($name, 0, $pos);
         $port = substr($name, $pos + 1);
     }
     #print __CLASS__.'->'.__FUNCTION__.': '.$name.', "'.$ip.'", "'.$port.'"'."\n";
 }
 protected function onOpen($connectionId, $info)
 {
     //it is called when the connection is open
     $message = 'пользователь #' . $connectionId . ' : ' . var_export($info, true) . ' ' . stream_socket_get_name($this->clients[$connectionId], true);
     foreach ($this->clients as $clientId => $client) {
         $this->sendToClient($clientId, $message);
     }
     $info['GET'];
     //or use $info['Cookie'] for use PHPSESSID or $info['X-Real-IP'] if you use proxy-server like nginx
     parse_str(substr($info['GET'], 1), $_GET);
     //parse get-query
     //var_export($_GET['id']);
     $this->userIds[$connectionId] = $_GET['userId'];
 }
Example #24
0
 public function start()
 {
     $socket = stream_socket_server($this->_host . ':' . $this->_port, $errno, $errstr);
     if (!$socket) {
         die("{$errstr} ({$errno})\n");
     }
     while ($connection = @stream_socket_accept($socket, -1)) {
         if (stream_socket_get_name($connection, true) !== false) {
             echo stream_socket_get_name($connection, true) . PHP_EOL;
         }
         $request = $this->_parseRequest($connection);
         $response = $this->_getResponse($request);
         fwrite($connection, $response['header'] . "\n\r" . $response['body']);
         fclose($connection);
     }
 }
Example #25
0
 /**
  * Initialize new client object wrapped by specified protocol
  *
  * @param resource $socket Stream socket resource of connection
  * @param React\EventLoop\LoopInterface $loop
  * @param protocolInterface             $protocol
  */
 public function __construct($socket, React\EventLoop\LoopInterface $loop, protocolInterface $protocol)
 {
     $this->clientConnection = new React\Socket\Connection($socket, $loop);
     $this->loop = $loop;
     $this->protocol = $protocol;
     $this->id = stream_socket_get_name($this->clientConnection->stream, false) . '<->' . stream_socket_get_name($this->clientConnection->stream, true);
     $this->protocol->on('command', function ($command) {
         $this->emit('command', [$command, $this]);
     });
     $this->clientConnection->on('data', [$this->protocol, 'onData']);
     $this->clientConnection->on('error', function ($error) {
         $this->emit('error', [$error, $this]);
     });
     $this->clientConnection->on('close', function () {
         $this->emit('close', [$this]);
     });
 }
Example #26
0
 public function run()
 {
     self::$rsa = new RSA();
     self::$rsa->setPrivate($this->rsaKey->getN(), $this->rsaKey->getE(), $this->rsaKey->getD());
     /* Need some improvement here, I know is weak :p */
     $sockets = array();
     while (true) {
         $read_socks = $sockets;
         $read_socks[] = $this->server;
         if (!stream_select($read_socks, $write, $except, 300000)) {
             die('something went wrong while selecting');
         }
         if (in_array($this->server, $read_socks)) {
             $new_client = stream_socket_accept($this->server);
             stream_set_blocking($new_client, 0);
             if (is_resource($new_client)) {
                 list($ip, $port) = explode(":", stream_socket_get_name($new_client, true));
                 $this->gameClientManager->addClient((int) $new_client, $new_client, $ip, $port, $this->logging);
                 echo 'Connection accepted from ' . stream_socket_get_name($new_client, true) . "\n";
                 $sockets[] = $new_client;
             }
             unset($read_socks[array_search($this->server, $read_socks)]);
         }
         foreach ($read_socks as $sock) {
             $gameClient = $this->gameClientManager->getClient((int) $sock);
             $buffer = fread($sock, 4096);
             if (!$buffer) {
                 echo 'Connection dropped from ' . stream_socket_get_name($sock, true) . "\n";
                 unset($sockets[array_search($sock, $sockets)]);
                 $this->gameClientManager->disposeClient((int) $sock);
                 continue;
             }
             if ($buffer == "<policy-file-request/>" . chr(0)) {
                 $gameClient->write('<?xml version="1.0"?><!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd"><cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>' . chr(0));
                 continue;
             }
             if ($gameClient->rc4initialized()) {
                 $buffer = $gameClient->getRc4client()->parse($buffer);
             }
             foreach ($this->bufferParser($buffer) as $packet) {
                 $this->packetManager->handlePacket($gameClient, new ClientMessage($packet));
             }
         }
     }
 }
 protected function onMessage($connectionId, $data, $type)
 {
     //вызывается при получении сообщения от клиента
     if (!strlen($data)) {
         return;
     }
     if ($login = array_search($connectionId, $this->logins)) {
         if (($tank = @json_decode($data, true)) && is_array($tank)) {
             //var_export($tank) . "\n";
             //$this->tanks[$connectionId] = $tank;
             //var_dump($this->tanks[$connectionId]);
             if (!empty($tank['move'])) {
                 $this->tanks[$connectionId]['dir'] = $tank['dir'];
                 $this->tanks[$connectionId]['move'] = true;
             }
             if (!empty($tank['fire']) && !isset($this->bullets[$connectionId])) {
                 $this->tanks[$connectionId]['fire'] = true;
             }
         } else {
             //антифлуд:
             $source = explode(':', stream_socket_get_name($this->getConnectionById($connectionId), true));
             $ip = $source[0];
             $time = time();
             if (isset($this->ips[$ip]) && $this->ips[$ip] == $time) {
                 return;
             } else {
                 $this->ips[$ip] = $time;
             }
             $message = $login . ': ' . strip_tags($data);
             $this->sendPacketToClients('message', $message);
         }
     } else {
         if (preg_match('/^[a-zA-Z0-9]{1,10}$/', $data, $match)) {
             if (isset($this->logins[$match[0]])) {
                 $this->sendPacketToClient($connectionId, 'message', 'Система: выбранное вами имя занято, попробуйте другое.');
             } else {
                 $this->logins[$match[0]] = $connectionId;
                 $this->sendPacketToClient($connectionId, 'message', 'Система: вы вошли в игру под именем ' . $match[0] . '. Для управления танком воспользуйтесь клавишами: вверх, вниз, вправо, влево или w s a d.');
                 $this->tanks[$connectionId] = array('name' => $match[0], 'x' => rand($this->tankmodelsize / 2, $this->w - $this->tankmodelsize / 2), 'y' => rand($this->tankmodelsize / 2, $this->h - $this->tankmodelsize / 2), 'dir' => 'up', 'health' => 0);
             }
         } else {
             $this->sendPacketToClient($connectionId, 'message', 'Система: ошибка при выборе имени. В имени можно использовать английские буквы и цифры. Имя не должно превышать 10 символов.');
         }
     }
 }
 protected function onMessage($connectionId, $data, $type)
 {
     //it is called when received a message from client
     if (!strlen($data)) {
         return;
     }
     if ($login = array_search($connectionId, $this->logins)) {
         if (($tank = @json_decode($data, true)) && is_array($tank)) {
             //var_export($tank) . "\n";
             //$this->tanks[$connectionId] = $tank;
             //var_dump($this->tanks[$connectionId]);
             if (!empty($tank['move'])) {
                 $this->tanks[$connectionId]['dir'] = $tank['dir'];
                 $this->tanks[$connectionId]['move'] = true;
             }
             if (!empty($tank['fire']) && !isset($this->bullets[$connectionId])) {
                 $this->tanks[$connectionId]['fire'] = true;
             }
         } else {
             //anti-flood:
             $source = explode(':', stream_socket_get_name($this->getConnectionById($connectionId), true));
             $ip = $source[0];
             $time = time();
             if (isset($this->ips[$ip]) && $this->ips[$ip] == $time) {
                 return;
             } else {
                 $this->ips[$ip] = $time;
             }
             $message = $login . ': ' . strip_tags($data);
             $this->sendPacketToClients('message', $message);
         }
     } else {
         if (preg_match('/^[a-zA-Z0-9]{1,10}$/', $data, $match)) {
             if (isset($this->logins[$match[0]])) {
                 $this->sendPacketToClient($connectionId, 'message', 'system: selected name already exists, try another.');
             } else {
                 $this->logins[$match[0]] = $connectionId;
                 $this->sendPacketToClient($connectionId, 'message', 'system: you are logged in as ' . $match[0] . '. For control the tank, use the keys: up, down, right, left or w s a d and space.');
                 $this->tanks[$connectionId] = array('name' => $match[0], 'x' => rand($this->tankmodelsize / 2, $this->w - $this->tankmodelsize / 2), 'y' => rand($this->tankmodelsize / 2, $this->h - $this->tankmodelsize / 2), 'dir' => 'up', 'health' => 0);
             }
         } else {
             $this->sendPacketToClient($connectionId, 'message', 'system: wrong name. Please enter valid name that will be displayed. The name can be used English letters and numbers. The name must not exceed 10 characters.');
         }
     }
 }
Example #29
0
 /**
  * Runs the server
  */
 public function run()
 {
     $this->_console("listening for connections on port %d", $this->_port);
     // loop for ever, this is going to be server
     while (true) {
         // keep selecting until there's something to do
         while (!($count = $this->_selector->select())) {
         }
         // when there's something to do loop over the ready set
         foreach ($this->_selector->selected_keys as $key) {
             try {
                 if ($key->isAcceptable()) {
                     // if the stream has connections ready to
                     // accept then accept them until there's no more
                     while ($stream = $key->stream->accept()) {
                         $this->_console("accepted connection from %s", stream_socket_get_name($stream->getStream(), true));
                         $this->_selector->register($stream, MioSelectionKey::OP_READ, new Timber_Connection());
                     }
                 } elseif ($key->isReadable()) {
                     $connection = $key->attachment;
                     $connection->read($key->stream, 25);
                     // check for a command to execute
                     if ($command = $connection->getCommand()) {
                         $this->_verbose("got a command: %s", $command->name);
                         $connection->ok($command->payloadsize);
                         $key->setInterestOps(MioSelectionKey::OP_WRITE);
                         // defer to relays
                         $this->_relayCommand($command);
                     }
                 } elseif ($key->isWritable()) {
                     $connection = $key->attachment;
                     $remaining = $connection->write($key->stream);
                     $key->setInterestOps($remaining ? MioSelectionKey::OP_WRITE : MioSelectionKey::OP_READ);
                 }
             } catch (MioClosedException $e) {
                 $this->_verbose("client disconnected without closing connection", true);
                 $this->_selector->removeKey($key);
             } catch (Exception $e) {
                 $this->_console($e->getMessage());
                 $this->_selector->removeKey($key);
             }
         }
     }
 }
Example #30
0
 /**
  * @covers React\Socket\Connection::getRemoteAddress
  */
 public function testGetRemoteAddress()
 {
     $loop = new StreamSelectLoop();
     $server = new Server($loop);
     $server->listen(0);
     $class = new \ReflectionClass('React\\Socket\\Server');
     $master = $class->getProperty('master');
     $master->setAccessible(true);
     $client = stream_socket_client('tcp://localhost:' . $server->getPort());
     $class = new \ReflectionClass('React\\Socket\\Connection');
     $method = $class->getMethod('parseAddress');
     $method->setAccessible(true);
     $servConn = new Connection($server->master, $loop);
     $mock = $this->expectCallableOnceWith($method->invokeArgs($servConn, array(stream_socket_get_name($master->getValue($server), false))));
     $server->on('connection', function ($conn) use($mock) {
         $mock($conn->getRemoteAddress());
     });
     $loop->tick();
 }