Beispiel #1
0
 protected function SendData($data, $id)
 {
     //Logger::getInstance()->outDebug("Send data to client #".$id.": ".$data);
     $result = event_buffer_write($this->buffers[$id], $data, strlen($data));
     if (!$result) {
         Logger::getInstance()->outError("Error while send data to client. Connection id: " . $id);
     }
 }
Beispiel #2
0
 public function endRequest($req, $appStatus, $protoStatus)
 {
     $connId = $req->attrs->connId;
     if (Daemon::$settings['logevents']) {
         Daemon::log('[WORKER ' . Daemon::$worker->pid . '] endRequest(' . implode(',', func_get_args()) . '): connId = ' . $connId . '.');
     }
     $c = pack('NC', $appStatus, $protoStatus) . "";
     Daemon::$worker->writePoolState[$connId] = TRUE;
     $w = event_buffer_write($this->buf[$connId], "" . "" . pack('nn', $req->attrs->id, strlen($c)) . "" . "" . $c);
     if ($protoStatus === -1) {
         $this->closeConnection($connId);
     } elseif (!Daemon::$parsedSettings['mod' . $this->modname . 'keepalive']) {
         $this->finishConnection($connId);
     }
 }
 public function handshake($headers)
 {
     $fnSockKey = function ($headers) {
         $lines = explode("\r\n", $headers);
         foreach ($lines as $line) {
             if (strpos($line, 'Sec-WebSocket-Key') === 0) {
                 $ex = explode(": ", $line);
                 return $ex[1];
             }
         }
     };
     $this->handshake = "HTTP/1.1 101 Switching Protocols\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "WebSocket-Origin: http://localhost\r\n" . "WebSocket-Location: ws://localhost:" . $this->server->getPort() . "\r\n" . "Sec-WebSocket-Accept: " . base64_encode(pack('H*', sha1($fnSockKey($headers) . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))) . "\r\n\r\n";
     event_buffer_write($this->buffer, $this->handshake, strlen($this->handshake));
     return true;
 }
Beispiel #4
0
 /**
  * Send data to the connection. Note that it just writes to buffer that flushes at every baseloop
  * @param string Data to send.
  * @return boolean Success.
  */
 public function write($s)
 {
     if (!$this->buffer) {
         return false;
     }
     if (!strlen($s)) {
         return true;
     }
     $this->sending = true;
     return event_buffer_write($this->buffer, $s);
 }
Beispiel #5
0
 private function make_offer()
 {
     $this->offer_socket = socket_create(AF_INET, SOCK_STREAM, 0);
     //socket_set_nonblock( $this->offer_socket ); // Maybe connect async (change callbacks, add write_offer)
     socket_connect($this->offer_socket, $this->offer_address, $this->offer_port);
     $this->offer_event = event_buffer_new($this->offer_socket, null, array($this, 'write_offer_success'), array($this, 'write_offer_error'), null);
     event_buffer_watermark_set($this->offer_event, EV_WRITE, 0, 0);
     event_buffer_base_set($this->offer_event, $this->event_base);
     event_buffer_enable($this->offer_event, EV_WRITE);
     $offer = pack('N', $this->worker_pid);
     event_buffer_write($this->offer_event, $offer);
 }
Beispiel #6
0
 public function writeHead($status = null, $reasonPhrase = null, $headers = null)
 {
     $addHeaders = array();
     $this->log("writeHead(..., ..., ...)");
     $args = func_get_args();
     if ($this->_wrote_head) {
         throw new \Exception("Already wrote head");
     }
     if (null === $status) {
         $status = $this->statusCode;
     }
     $this->statusCode = $status;
     if (null === $reasonPhrase) {
         $reasonPhrase = "OK";
     } else {
         if (is_array($reasonPhrase)) {
             $addHeaders = $reasonPhrase;
             $reasonPhrase = "OK";
         } else {
             if (null === $headers) {
                 $addHeaders = array();
                 if (is_array($headers)) {
                     $addHeaders = $headers;
                 }
             }
         }
     }
     $outputHeaders = $this->_headers;
     foreach ($addHeaders as $key => $value) {
         $outputHeaders[$key] = $value;
     }
     $result = "HTTP/" . $this->_request->httpVersion;
     $result .= " {$status} {$reasonPhrase}\r\n";
     foreach ($outputHeaders as $key => $value) {
         $result .= "{$key}: {$value}\r\n";
     }
     $result .= "\r\n";
     $this->_wrote_head = true;
     event_buffer_write($this->ev_buffer, $result);
 }
Beispiel #7
0
 private function attempt_handshake($buffer, $conn)
 {
     $data = event_buffer_read($buffer, 1024);
     $lines = preg_split("/\r\n/", $data);
     $headers = array();
     foreach ($lines as $line) {
         $line = chop($line);
         if (preg_match('/\\A(\\S+): (.*)\\z/', $line, $matches)) {
             $headers[$matches[1]] = $matches[2];
         }
     }
     if (isset($headers['Sec-WebSocket-Key'])) {
         $host =& $this->host;
         $port =& $this->port;
         $secKey = $headers['Sec-WebSocket-Key'];
         $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
         $upgrade = "HTTP/1.1 101 Switching Protocols\r\n" . "Server: Thalassa V-1.0\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "WebSocket-Origin: {$host}\r\n" . "WebSocket-Location: ws://{$host}:{$port}\r\n" . "Sec-Websocket-Protocol: wamp.2.json\r\n" . "Sec-WebSocket-Accept: {$secAccept}\r\n\r\n";
         if (event_buffer_write($buffer, $upgrade)) {
             $this->monitor($conn, $buffer);
         } else {
             $this->abort_handshake($conn);
         }
     } else {
         $this->abort_handshake($conn);
     }
 }
 protected function _write($connectionId, $data, $delimiter = '')
 {
     event_buffer_write($this->buffers[$connectionId], $data . $delimiter);
 }
 function ev_read($buffer, $id)
 {
     static $ct = 0;
     $ct_last = $ct;
     $ct_data = '';
     while ($read = event_buffer_read($buffer, 1024)) {
         $ct += strlen($read);
         $ct_data .= $read;
     }
     $datamsg = '收到数据来自ID:' . $id . ' 内容:' . $ct_data;
     $datamsg = iconv('utf-8', 'gbk', $datamsg);
     echo $datamsg . "\n";
     if ($ct_data == '00') {
         //收到来自打印机的心跳数据 给打印机下发数据
         $clientimei = self::$imei[$id];
         $data811 = '%30测试数据';
         $data811 .= '%%%00你的IMEI如下:';
         $data811 .= '%%' . $clientimei;
         $data811 .= '1234:###' . iconv('utf-8', 'gbk', $data811);
         $fblen = $this->jsdata($data811);
         $write = '1123456789' . $fblen . '81101   1' . $data811 . '#';
         event_buffer_write($buffer, $write);
     } else {
         $type = substr($ct_data, 20, 3);
         //各类方法
         if ($type == '810') {
             //拿810 取IMEI
             self::$imei[$id] = substr($ct_data, 23, 15);
         }
     }
 }
Beispiel #10
0
function ev_read($buffer, $id)
{
    global $clients;
    global $redis;
    while ($read = event_buffer_read($buffer, 1024)) {
        $clients[$id]['read_buffer'] .= $read;
    }
    // Determine if the buffer is ready
    // The are two states when we determine if the buffer is ready.
    // State 1 is the command state, when we wait for a command from
    // the client
    // State 2 is the DATA state, when the client sends the data
    // for the email.
    if ($clients[$id]['state'] === 1) {
        // command state, strings terminate with \r\n
        if (strlen($clients[$id]['read_buffer']) > 1 && strpos($clients[$id]['read_buffer'], "\r\n", strlen($clients[$id]['read_buffer']) - 2) !== false) {
            $clients[$id]['read_buffer_ready'] = true;
        }
    } elseif ($clients[$id]['state'] === 2) {
        // DATA reading state
        // not ready unless you get a \r\n.\r\n at the end
        $len = strlen($clients[$id]['read_buffer']);
        if ($len > GSMTP_MAX_SIZE || $len > 4 && strpos($clients[$id]['read_buffer'], "\r\n.\r\n", $len - 5) !== false) {
            $clients[$id]['read_buffer_ready'] = true;
            // finished
            $clients[$id]['read_buffer'] = substr($clients[$id]['read_buffer'], 0, $len - 5);
        }
    } elseif ($clients[$id]['state'] === 3) {
        $clients[$id]['read_buffer_ready'] = true;
        // finished
    }
    if (!$redis) {
        //error_log("no redis ev read: ".var_dump($redis));
    }
    process_smtp($id);
    if (strlen($clients[$id]['response']) > 0) {
        event_buffer_write($buffer, $clients[$id]['response']);
        add_response($id, null);
    }
}
 function ev_read($buffer, $id)
 {
     $data = '';
     while ($read = event_buffer_read($buffer, 1024)) {
         $data .= $read;
     }
     if (APP_DEBUG === true) {
         Log::write("eSeal[{$id}] " . __METHOD__ . " > " . $data, Log::INFO);
     }
     if ($data == 'QUIT') {
         $this->_closeConnections();
     } else {
         if ($data == 'PING') {
             //ping的时候服务器返回服务器的时间
             event_buffer_write($buffer, date('Y-m-d H:i:s'));
         } else {
             $this->_processSeal($data);
         }
     }
 }
Beispiel #12
0
 public function write($connId, $s)
 {
     Debug::netEvent(get_class($this) . '::' . __METHOD__ . '(' . $connId . ',' . strlen($s) . ') invoked. ');
     // 如果连接已经关闭了, bufferEv 已经被销毁,这里不能执行 buffer_write
     if (!isset($this->connEvBufPool[$connId])) {
         Debug::netErrorEvent(get_class($this) . '::' . __METHOD__ . '(' . $connId . ',' . strlen($s) . ')(' . substr($s, 0, 50) . ') already closed, skip write. ');
         return FALSE;
     }
     return event_buffer_write($this->connEvBufPool[$connId], $s);
 }
 public function ev_read($buffer, $id)
 {
     static $ct = 0;
     $ct_last = $ct;
     $ct_data = '';
     // event_buffer_read — Read data from a buffered event
     while ($read = event_buffer_read($buffer, 1024)) {
         $ct += strlen($read);
         $ct_data .= $read;
     }
     $ct_size = ($ct - $ct_last) * 8;
     echo "[{$id}]" . __METHOD__ . " > " . $ct_data . "\n";
     event_buffer_write($buffer, "Received {$ct_size} byte data.\r\n");
 }
Beispiel #14
0
 /**
  * Sends some data
  */
 public function write($data)
 {
     event_buffer_write($this->event, $data);
     return $this;
 }
Beispiel #15
0
 /**
  * Reads data from the connection's buffer.
  * @param integer Connection's ID.
  * @return void
  */
 public function readConn($connId)
 {
     $buf = $this->read($connId, $this->readPacketSize);
     if (sizeof($this->poolState[$connId]) < 3) {
         return;
     }
     if ($this->poolState[$connId]['state'] === 0) {
         if (Daemon::$appResolver->checkAppEnabled('FlashPolicy')) {
             if (strpos($buf, '<policy-file-request/>') !== false) {
                 if (($FP = Daemon::$appResolver->getInstanceByAppName('FlashPolicy')) && $FP->policyData) {
                     Daemon::$process->writePoolState[$connId] = true;
                     event_buffer_write($this->buf[$connId], $FP->policyData . "");
                 }
                 $this->finishConnection($connId);
                 return;
             }
         }
         ++$this->poolState[$connId]['n'];
         $rid = ++Daemon::$process->reqCounter;
         $this->poolState[$connId]['state'] = 1;
         $req = new stdClass();
         $req->attrs = new stdClass();
         $req->attrs->request = array();
         $req->attrs->get = array();
         $req->attrs->post = array();
         $req->attrs->cookie = array();
         $req->attrs->server = array();
         $req->attrs->files = array();
         $req->attrs->session = null;
         $req->attrs->connId = $connId;
         $req->attrs->id = $this->poolState[$connId]['n'];
         $req->attrs->params_done = false;
         $req->attrs->stdin_done = false;
         $req->attrs->stdinbuf = '';
         $req->attrs->stdinlen = 0;
         $req->attrs->inbuf = '';
         $req->attrs->chunked = false;
         $req->queueId = $rid;
         if ($this->config->logqueue->value) {
             Daemon::$process->log('new request queued.');
         }
         Daemon::$process->queue[$rid] = $req;
         $this->poolQueue[$connId][$req->attrs->id] = $req;
     } else {
         $rid = $this->poolQueue[$connId][$this->poolState[$connId]['n']]->queueId;
         if (isset(Daemon::$process->queue[$rid])) {
             $req = Daemon::$process->queue[$rid];
         } else {
             Daemon::log('Unexpected input. Request ID: ' . $rid . '.');
             return;
         }
     }
     if ($this->poolState[$connId]['state'] === 1) {
         $req->attrs->inbuf .= $buf;
         if (Daemon::$appResolver->checkAppEnabled('FlashPolicy')) {
             if (strpos($req->attrs->inbuf, '<policy-file-request/>') !== false) {
                 if (($FP = Daemon::$appResolver->getInstanceByAppName('FlashPolicy')) && $FP->policyData) {
                     Daemon::$process->writePoolState[$req->attrs->connId] = true;
                     event_buffer_write($this->buf[$req->attrs->connId], $FP->policyData . "");
                 }
                 $this->finishConnection($req->attrs->connId);
                 return;
             }
         }
         $buf = '';
         if (($p = strpos($req->attrs->inbuf, "\r\n\r\n")) !== false) {
             $headers = binarySubstr($req->attrs->inbuf, 0, $p);
             $h = explode("\r\n", $headers);
             $req->attrs->inbuf = binarySubstr($req->attrs->inbuf, $p + 4);
             $e = explode(' ', $h[0]);
             $u = parse_url($e[1]);
             $req->attrs->server['REQUEST_METHOD'] = $e[0];
             $req->attrs->server['REQUEST_URI'] = $u['path'] . (isset($u['query']) ? '?' . $u['query'] : '');
             $req->attrs->server['DOCUMENT_URI'] = $u['path'];
             $req->attrs->server['PHP_SELF'] = $u['path'];
             $req->attrs->server['QUERY_STRING'] = isset($u['query']) ? $u['query'] : null;
             $req->attrs->server['SCRIPT_NAME'] = $req->attrs->server['DOCUMENT_URI'] = isset($u['path']) ? $u['path'] : '/';
             $req->attrs->server['SERVER_PROTOCOL'] = $e[2];
             list($req->attrs->server['REMOTE_ADDR'], $req->attrs->server['REMOTE_PORT']) = explode(':', $this->poolState[$connId]['addr']);
             for ($i = 1, $n = sizeof($h); $i < $n; ++$i) {
                 $e = explode(': ', $h[$i]);
                 if (isset($e[1])) {
                     $req->attrs->server['HTTP_' . strtoupper(strtr($e[0], HTTPRequest::$htr))] = $e[1];
                 }
             }
             $req->attrs->params_done = true;
             if (isset($req->attrs->server['HTTP_CONNECTION']) && $req->attrs->server['HTTP_CONNECTION'] === 'Upgrade' && isset($req->attrs->server['HTTP_UPGRADE']) && $req->attrs->server['HTTP_UPGRADE'] === 'WebSocket') {
                 if ($this->WS) {
                     $this->WS->inheritFromRequest($req, $this);
                     return;
                 }
             } else {
                 $req = Daemon::$appResolver->getRequest($req, $this, isset($this->config->responder->value) ? $this->config->responder->value : null);
             }
             if ($req instanceof stdClass) {
                 $this->endRequest($req, 0, 0);
                 unset(Daemon::$process->queue[$rid]);
             } else {
                 if ($this->config->sendfile->value && (!$this->config->sendfileonlybycommand->value || isset($req->attrs->server['USE_SENDFILE'])) && !isset($req->attrs->server['DONT_USE_SENDFILE'])) {
                     $fn = tempnam($this->config->sendfiledir->value, $this->config->sendfileprefix->value);
                     $req->sendfp = fopen($fn, 'wb');
                     $req->header('X-Sendfile: ' . $fn);
                 }
                 $req->stdin($req->attrs->inbuf);
                 $req->attrs->inbuf = '';
                 $this->poolQueue[$connId][$req->attrs->id] = $req;
                 $this->poolState[$connId]['state'] = 2;
             }
         }
     }
     if ($this->poolState[$connId]['state'] === 2) {
         $req->stdin($buf);
         if (Daemon::$config->logevents->value) {
             Daemon::log('stdin_done = ' . ($req->attrs->stdin_done ? '1' : '0'));
         }
         if ($req->attrs->stdin_done) {
             $this->poolState[$req->attrs->connId]['state'] = 0;
         }
     }
     if ($req->attrs->stdin_done && $req->attrs->params_done) {
         if ($this->variablesOrder === null) {
             $req->attrs->request = $req->attrs->get + $req->attrs->post + $req->attrs->cookie;
         } else {
             for ($i = 0, $s = strlen($this->variablesOrder); $i < $s; ++$i) {
                 $char = $this->variablesOrder[$i];
                 if ($char == 'G') {
                     $req->attrs->request += $req->attrs->get;
                 } elseif ($char == 'P') {
                     $req->attrs->request += $req->attrs->post;
                 } elseif ($char == 'C') {
                     $req->attrs->request += $req->attrs->cookie;
                 }
             }
         }
         Daemon::$process->timeLastReq = time();
     }
 }
Beispiel #16
0
 public function readConn($connId)
 {
     static $roles = array(1 => 'FCGI_RESPONDER', 2 => 'FCGI_AUTHORIZER', 3 => 'FCGI_FILTER');
     $buf = $this->read($connId, $this->readPacketSize);
     if (sizeof($this->poolState[$connId]) < 3) {
         return;
     }
     if ($this->poolState[$connId]['state'] === 0) {
         if (strpos($buf, '<policy-file-request/>') !== FALSE) {
             if (($FP = Daemon::$appResolver->getInstanceByAppName('FlashPolicy')) && $FP->policyData) {
                 Daemon::$worker->writePoolState[$connId] = TRUE;
                 event_buffer_write($this->buf[$connId], $FP->policyData . "");
             }
             $this->finishConnection($connId);
             return;
         }
         ++Daemon::$worker->queryCounter;
         ++$this->poolState[$connId]['n'];
         $rid = $connId . '-' . $this->poolState[$connId]['n'];
         $this->poolState[$connId]['state'] = 1;
         $req = new stdClass();
         $req->attrs = new stdClass();
         $req->attrs->request = array();
         $req->attrs->get = array();
         $req->attrs->post = array();
         $req->attrs->cookie = array();
         $req->attrs->server = array();
         $req->attrs->files = array();
         $req->attrs->session = NULL;
         $req->attrs->connId = $connId;
         $req->attrs->id = $this->poolState[$connId]['n'];
         $req->attrs->params_done = FALSE;
         $req->attrs->stdin_done = FALSE;
         $req->attrs->stdinbuf = '';
         $req->attrs->stdinlen = 0;
         $req->attrs->inbuf = '';
         $req->attrs->chunked = FALSE;
         if (Daemon::$settings['mod' . $this->modname . 'logqueue']) {
             Daemon::log('[WORKER ' . Daemon::$worker->pid . '] new request queued.');
         }
         Daemon::$worker->queue[$rid] = $req;
         $this->poolQueue[$connId][$req->attrs->id] = $req;
     } else {
         $rid = $connId . '-' . $this->poolState[$connId]['n'];
         if (isset(Daemon::$worker->queue[$rid])) {
             $req = Daemon::$worker->queue[$rid];
         } else {
             Daemon::log('Unexpected input. Request ID: ' . $rid . '.');
             return;
         }
     }
     if ($this->poolState[$connId]['state'] === 1) {
         $req->attrs->inbuf .= $buf;
         if (strpos($req->attrs->inbuf, '<policy-file-request/>') !== FALSE) {
             if (($FP = Daemon::$appResolver->getInstanceByAppName('FlashPolicy')) && $FP->policyData) {
                 Daemon::$worker->writePoolState[$req->attrs->connId] = TRUE;
                 event_buffer_write($this->buf[$req->attrs->connId], $FP->policyData . "");
             }
             $this->finishConnection($req->attrs->connId);
             return;
         }
         $buf = '';
         if (($p = strpos($req->attrs->inbuf, "\r\n\r\n")) !== FALSE) {
             $headers = binarySubstr($req->attrs->inbuf, 0, $p);
             $h = explode("\r\n", $headers);
             $req->attrs->inbuf = binarySubstr($req->attrs->inbuf, $p + 4);
             $e = explode(' ', $h[0]);
             $u = parse_url($e[1]);
             $req->attrs->server['REQUEST_METHOD'] = $e[0];
             $req->attrs->server['REQUEST_URI'] = $u['path'] . (isset($u['query']) ? '?' . $u['query'] : '');
             $req->attrs->server['DOCUMENT_URI'] = $u['path'];
             $req->attrs->server['PHP_SELF'] = $u['path'];
             $req->attrs->server['QUERY_STRING'] = isset($u['query']) ? $u['query'] : NULL;
             $req->attrs->server['SCRIPT_NAME'] = $req->attrs->server['DOCUMENT_URI'] = isset($u['path']) ? $u['path'] : '/';
             $req->attrs->server['SERVER_PROTOCOL'] = $e[2];
             list($req->attrs->server['REMOTE_ADDR'], $req->attrs->server['REMOTE_PORT']) = explode(':', $this->poolState[$connId]['addr']);
             for ($i = 1, $n = sizeof($h); $i < $n; ++$i) {
                 $e = explode(': ', $h[$i]);
                 if (isset($e[1])) {
                     $req->attrs->server['HTTP_' . strtoupper(strtr($e[0], Request::$htr))] = $e[1];
                 }
             }
             $req->attrs->params_done = TRUE;
             if (isset($req->attrs->server['HTTP_CONNECTION']) && $req->attrs->server['HTTP_CONNECTION'] === 'Upgrade' && isset($req->attrs->server['HTTP_UPGRADE']) && $req->attrs->server['HTTP_UPGRADE'] === 'WebSocket') {
                 if ($this->WS) {
                     $this->WS->inheritFromRequest($req, $this);
                     return;
                 }
             } else {
                 $req = Daemon::$appResolver->getRequest($req, $this, isset(Daemon::$settings[$k = 'mod' . $this->modname . 'responder']) ? Daemon::$settings[$k] : NULL);
             }
             if ($req instanceof stdClass) {
                 $this->endRequest($req, 0, 0);
                 unset(Daemon::$worker->queue[$rid]);
             } else {
                 if (Daemon::$settings['mod' . $this->modname . 'sendfile'] && (!Daemon::$settings['mod' . $this->modname . 'sendfileonlybycommand'] || isset($req->attrs->server['USE_SENDFILE'])) && !isset($req->attrs->server['DONT_USE_SENDFILE'])) {
                     $fn = tempnam(Daemon::$settings['mod' . $this->modname . 'sendfiledir'], Daemon::$settings['mod' . $this->modname . 'sendfileprefix']);
                     $req->sendfp = fopen($fn, 'wb');
                     $req->header('X-Sendfile: ' . $fn);
                 }
                 $req->stdin($req->attrs->inbuf);
                 $req->attrs->inbuf = '';
                 Daemon::$worker->queue[$rid] = $req;
                 $this->poolQueue[$connId][$req->attrs->id] = $req;
                 $this->poolState[$connId]['state'] = 2;
             }
         }
     }
     if ($this->poolState[$connId]['state'] === 2) {
         $req->stdin($buf);
         if (Daemon::$settings['logevents']) {
             Daemon::log('stdin_done = ' . ($req->attrs->stdin_done ? '1' : '0'));
         }
         if ($req->attrs->stdin_done) {
             $this->poolState[$req->attrs->connId]['state'] = 0;
         }
     }
     if ($req->attrs->stdin_done && $req->attrs->params_done) {
         if (($order = ini_get('request_order')) || ($order = ini_get('variables_order'))) {
             for ($i = 0, $s = strlen($order); $i < $s; ++$i) {
                 $char = $order[$i];
                 if ($char == 'G') {
                     $req->attrs->request += $req->attrs->get;
                 } elseif ($char == 'P') {
                     $req->attrs->request += $req->attrs->post;
                 } elseif ($char == 'C') {
                     $req->attrs->request += $req->attrs->cookie;
                 }
             }
         } else {
             $req->attrs->request = $req->attrs->get + $req->attrs->post + $req->attrs->cookie;
         }
         $this->timeLastReq = time();
     }
 }
 /**
  * Wyslanie podanej wiadomosci do podlaczonego klienta
  * @param string $pMessage                 wiadomosc do wyslania
  * @return boolean                         czy wiadomosc zostala wyslana
  */
 public function send($pMessage)
 {
     if (strlen($pMessage) > 1) {
         if ("\r\n" !== substr($pMessage, -2)) {
             $pMessage .= "\r\n";
         }
         event_buffer_write($this->eventBuffer, $pMessage, strlen($pMessage));
         $this->flush();
     }
     return true;
 }
 /**
  * Send 404 error to client.
  * @param <type> $BufferEvent
  * @param <type> $SocketName
  * @return boolean
  */
 private function Send404Error()
 {
     $Message = "File not found!";
     $Data = "HTTP/1.0 404 Not Found\r\n" . "Content-Type: text/plain; charset=UTF-8\r\n" . "Connection: close\r\n" . "Content-Length: " . strlen($Message) . "\r\n\r\n{$Message}";
     event_buffer_write($this->BufferEvent, $Data);
     $this->DataFin = true;
     return true;
 }
Beispiel #19
0
 /**
  * Writes data to the stream
  *
  * @param string $data
  * @return bool
  */
 public function write($data)
 {
     return event_buffer_write($this->resource, $data);
 }
Beispiel #20
0
 /**
  * Writes data to the specified buffered event.
  *
  * @see event_buffer_write
  *
  * @throws EventException
  *
  * @param string $data The data to be written.
  * @param integer $dataSize Optional size parameter. Writes all the data by default
  *
  * @return EventBuffer
  */
 public function write($data, $dataSize = -1)
 {
     if (!event_buffer_write($this->resource, $data, $dataSize)) {
         throw $this->exception('Could not write data to the buffered event (event_buffer_write).');
     }
     return $this;
 }
 protected function deframe($message, &$user, $id = null)
 {
     //echo $this->strtohex($message);
     $headers = $this->extractHeaders($message);
     $pongReply = false;
     $willClose = false;
     switch ($headers['opcode']) {
         case 0:
         case 1:
         case 2:
             break;
         case 8:
             // todo: close the connection
             $user['hasSentClose'] = true;
             return "";
         case 9:
             $pongReply = true;
         case 10:
             break;
         default:
             $willClose = true;
             break;
     }
     if ($user['handlingPartialPacket']) {
         $message = $user['partialBuffer'] . $message;
         $user['handlingPartialPacket'] = false;
         return $this->deframe($message, $user, $id);
     }
     if ($this->checkRSVBits($headers, $user)) {
         return false;
     }
     if ($willClose) {
         return false;
     }
     $payload = $user['partialMessage'] . $this->extractPayload($message, $headers);
     if ($pongReply) {
         $reply = $this->frame($payload, $user, 'pong');
         event_buffer_write(self::$buffers[$id], $reply);
         return false;
     }
     if (extension_loaded('mbstring')) {
         if ($headers['length'] > mb_strlen($this->applyMask($headers, $payload))) {
             $user['handlingPartialPacket'] = true;
             $user['partialBuffer'] = $message;
             return false;
         }
     } else {
         if ($headers['length'] > strlen($this->applyMask($headers, $payload))) {
             $user['handlingPartialPacket'] = true;
             $user['partialBuffer'] = $message;
             return false;
         }
     }
     $payload = $this->applyMask($headers, $payload);
     if ($headers['fin']) {
         $user['partialMessage'] = "";
         return $payload;
     }
     $user['partialMessage'] = $payload;
     return false;
 }
 public function writeToBuffer($conn_id, $data)
 {
     $result = event_buffer_write($this->connection_buffers[$conn_id], $data);
     self::log('Connection', $conn_id, 'wrote ' . strlen($data) . ' chars to buffer');
     return $result;
 }
Beispiel #23
0
 public function write($message)
 {
     event_buffer_write($this->buffer, $message, strlen($message));
 }
 public function write($s)
 {
     $b = $this->writeBuf !== NULL ? $this->writeBuf : $this->readBuf;
     if ($b === FALSE) {
         return $this;
     }
     if ($s !== '') {
         $this->writeState = TRUE;
     }
     if (!event_buffer_write($b, $s)) {
         throw new Exception('write() failed.');
     }
     return $this;
 }
 public function write($connId, $s)
 {
     Daemon::$worker->writePoolState[$connId] = TRUE;
     if (!isset($this->buf[$connId])) {
         if (isset($this->sessions[$connId])) {
             $this->sessions[$connId]->finish();
         }
         return FALSE;
     }
     return event_buffer_write($this->buf[$connId], $s);
 }
Beispiel #26
0
 /**
  * Handles the output from downstream requests.
  * @return void
  */
 public function endRequest($req, $appStatus, $protoStatus)
 {
     $connId = $req->attrs->connId;
     if ($this->config->logevents->value) {
         Daemon::$process->log('endRequest(' . implode(',', func_get_args()) . '): connId = ' . $connId . '.');
     }
     $c = pack('NC', $appStatus, $protoStatus) . "";
     if (!isset($this->buf[$connId])) {
         return;
     }
     Daemon::$process->writePoolState[$connId] = true;
     $w = event_buffer_write($this->buf[$connId], "" . "" . pack('nn', $req->attrs->id, strlen($c)) . "" . "" . $c);
     if ($protoStatus === -1) {
         $this->closeConnection($connId);
     } elseif (!$this->config->keepalive->value) {
         $this->finishConnection($connId);
     }
 }