public function run($force = false) { if ($force) { $this->killProgramsOnDreddPort(); } $socket = sprintf('tcp://%s:%s', $this->host, $this->port); $server = stream_socket_server($socket, $errno, $errorMessage); if ($server === false) { throw new UnexpectedValueException("Server could not bind to socket: {$errorMessage}"); } $buffer = ""; for (;;) { $client = stream_socket_accept($server); while ($socketData = stream_socket_recvfrom($client, self::RECV_LENGTH)) { $buffer .= $socketData; // determine if message terminating character is present. if (strpos($buffer, self::MESSAGE_END) === false) { continue; } $messages = []; foreach (explode(self::MESSAGE_END, $buffer) as $data) { $message = json_decode($data); // if not valid json the partial message needs saved if (!$message) { $buffer = $message; continue; } $messages[] = $message; } foreach ($messages as $message) { $this->processMessage($message, $client); } } } }
function sw_server_handle_recvfrom($server_socket, $events, $server) { $data = stream_socket_recvfrom($server_socket, $server->buffer_size, $server->flags, $peer); if ($data !== false && $data != '') { $server->protocol->onData($peer, $data); } }
/** * {@inheritdoc} */ public function read($length) { if (!$this->isReadable()) { throw new RuntimeException("Stream is not readable"); } return stream_socket_recvfrom($this->getContext(), $length); }
public function query($text) { $head = <<<_HEADER_ <?xml version="1.0" ?> <wordsegmentation version="0.1"> <option showcategory="1" /> <authentication username="******" password="******" /> <text> _HEADER_; $footer = <<<_FOOT_ </text> </wordsegmentation> _FOOT_; $this->data_send = $text; $text = str_replace("&", " ", $text); $querystr = $head . $text . $footer; $tempxml = simplexml_load_string($querystr); $resp = array(); if ($tempxml) { if (stream_socket_sendto($this->sock, $tempxml->asXML())) { do { $ttt = stream_socket_recvfrom($this->sock, 65525); $ttt = iconv('big5', 'utf-8', $ttt); $resp[] = $ttt; } while (!simplexml_load_string(implode($resp))); return $this->data_recv = html_entity_decode(implode($resp)); } } else { $this->data_recv = 0; return null; } }
/** * {@inheritdoc} */ public function enableCrypto(int $method, float $timeout = 0) : \Generator { $resource = $this->getResource(); if ($method & 1 || 0 === $method) { yield from $this->await($timeout); } else { yield from $this->poll($timeout); $raw = stream_socket_recvfrom($resource, 11, STREAM_PEEK); if (11 > strlen($raw)) { throw new FailureException('Failed to read crypto handshake.'); } $data = unpack('ctype/nversion/nlength/Nembed/nmax-version', $raw); if (0x16 !== $data['type']) { throw new FailureException('Invalid crypto handshake.'); } $version = $this->selectCryptoVersion($data['max-version']); if ($method & $version) { // Check if version was available in $method. $method = $version; } } do { // Error reporting suppressed since stream_socket_enable_crypto() emits E_WARNING on failure. $result = @stream_socket_enable_crypto($resource, (bool) $method, $method); } while (0 === $result && !(yield from $this->poll($timeout))); if ($result) { $this->crypto = $method; return; } $message = 'Failed to enable crypto.'; if ($error = error_get_last()) { $message .= sprintf(' Errno: %d; %s', $error['type'], $error['message']); } throw new FailureException($message); }
public function send($socket) { $deferred = new Deferred(); stream_set_blocking($socket, false); $data = $this->getRequest(); \Amp\onWritable($socket, function ($writer, $socket) use($deferred, &$data) { if ($bytes = fwrite($socket, $data)) { if ($bytes < \strlen($data)) { $data = substr($data, $bytes); return; } $size = 8192; \Amp\onReadable($socket, function ($reader, $socket) use($deferred, &$size) { /* make attention to not read too much data */ $data = stream_socket_recvfrom($socket, $size, STREAM_PEEK); if (false === ($pos = strpos($data, "\r\n\r\n"))) { if (\strlen($data) == $size) { $size *= 2; // unbounded?? } return; } \Amp\cancel($reader); $deferred->succeed($this->parseResponse(fread($socket, $pos + 4))); }); } else { $deferred->succeed(null); } \Amp\cancel($writer); }); return $deferred->promise(); }
/** * @medium * @group connected * @expectedException \Predis\Protocol\ProtocolException */ public function testThrowsExceptionOnProtocolDesynchronizationErrors() { $connection = $this->createConnection(); $stream = $connection->getResource(); $connection->writeRequest($this->getCurrentProfile()->createCommand('ping')); stream_socket_recvfrom($stream, 1); $connection->read(); }
public function handleData($stream) { $data = stream_socket_recvfrom($stream, $this->bufferSize); if ('' === $data || false === $data || feof($stream)) { $this->end(); } else { $this->emit('data', array($data, $this)); } }
/** {@inheritdoc} */ public function read(FramePickerInterface $picker, Context $context, $isOutOfBand) { stream_socket_recvfrom($this->socket->getStreamResource(), self::SOCKET_BUFFER_SIZE, STREAM_PEEK, $remoteAddress); if (!$remoteAddress && !$this->isLocalIo) { stream_socket_recvfrom($this->socket->getStreamResource(), self::SOCKET_BUFFER_SIZE); throw new AcceptException($this->socket, 'Can not accept client: failed to receive remote address.'); } $reader = new DatagramClientIo($this->socket, $this->isLocalIo ? null : $remoteAddress); return new AcceptedFrame($remoteAddress, new UdpClientSocket($this->socket, $remoteAddress, $reader->read(new RawFramePicker(), $context, $isOutOfBand))); }
public function handleData($socket) { $data = @stream_socket_recvfrom($socket, $this->bufferSize); if ('' === $data || false === $data) { $this->handleDisconnect($socket); $this->loop->removeStream($socket); } else { $client = $this->getClient($socket); $client->emit('data', array($data)); } }
function handleRecv($sock) { $pkt = stream_socket_recvfrom($sock, self::MAX_PACKET_SIZE, 0, $peer); if ($pkt == false) { $this->emit('error', array("Reading packet from {$peer} failed")); return; } if ($pkt != "") { $this->emit('packet', array($pkt, $peer, $this)); } }
function process() { $request = stream_socket_recvfrom($this->srv, 1500, 0, $this->cli); if ($request == false) { cy_log(CYE_ERROR, "read request from srv fd error."); return false; } $this->request_init(); $this->request($request); $this->request_shutdown(); }
public function handleData($stream) { // Socket is raw, not using fread as it's interceptable by filters // See issues #192, #209, and #240 $data = stream_socket_recvfrom($stream, $this->bufferSize); if ('' === $data || false === $data || feof($stream)) { $this->end(); } else { $this->emit('data', array($data, $this)); } }
public function read($stream) { // Socket is raw, not using fread as it's interceptable by filters // See issues #192, #209, and #240 $data = stream_socket_recvfrom($stream, $this->bufferSize); if ('' !== $data && false !== $data) { $this->notifyNext(new StreamEvent("/stream/data", $data)); } if ('' === $data || false === $data || !is_resource($stream) || feof($stream)) { $this->notifyCompleted(); } }
public function server() { $socket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr, STREAM_SERVER_BIND); if (!$socket) { die("{$errstr} ({$errno})"); } do { $pkt = stream_socket_recvfrom($socket, 1, 0, $peer); echo $pkt, "\n"; echo "{$peer}\n"; //stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer); } while (true); }
public function read() { $data = stream_socket_recvfrom($this->socket, $this->bufferSize, 0, $peerAddress); if ($data === false) { // receiving data failed => remote side rejected one of our packets // due to the nature of UDP, there's no way to tell which one exactly // $peer is not filled either $this->notifyError(new \Exception('Invalid message')); return; } $this->notifyNext(new StreamEvent("/datagram/data", $data, ["peer" => $peerAddress])); $this->close(); }
/** * Accept a connection * * @return bool|mixed */ public function accept() { if (($client = stream_socket_accept($this->socket)) === false) { // @codeCoverageIgnoreStart return false; // @codeCoverageIgnoreEnd } $data = ''; while (($buf = stream_socket_recvfrom($client, 1024)) !== '') { $data .= $buf; } fclose($client); return unserialize($data); }
function server_loop() { while (true) { $data = ''; while (true) { $buf = stream_socket_recvfrom($this->server_sock, $this->buffer_size, 0, $peer); $data .= $buf; if ($buf === null or strlen($buf) < $this->buffer_size) { break; } } $this->protocol->onData($peer, $data); } }
/** {@inheritdoc} */ protected function readRawDataIntoPicker(FramePickerInterface $picker, $isOutOfBand) { $size = self::SOCKET_BUFFER_SIZE; $resource = $this->socket->getStreamResource(); do { $data = stream_socket_recvfrom($resource, $size, STREAM_PEEK); if (strlen($data) < $size) { break; } $size += $size; } while (true); $data = stream_socket_recvfrom($resource, $size, 0, $actualRemoteAddress); return $picker->pickUpData($data, $actualRemoteAddress); }
/** Bi-directional UDP communication @param $msg the message @param $port integer port @return the response or an empty string Whatever program is listening on the other end cannot respond on the same port. It must send the response on (port+1). */ public static function udpPoke($msg, $port = 9450) { $socket = stream_socket_server("udp://127.0.0.1:" . ($port + 1), $errno, $errstr, STREAM_SERVER_BIND); self::udpSend($msg, $port); $read = array($socket); $write = null; $except = null; $ready = stream_select($read, $write, $except, 0, 500); $buf = ""; if ($ready > 0) { $buf = stream_socket_recvfrom($socket, 1024, 0, $peer); } stream_socket_shutdown($socket, STREAM_SHUT_RDWR); return $buf; }
function run() { unlink(__DIR__ . '/alloc.log'); unlink(__DIR__ . '/free.log'); $socket = stream_socket_server("udp://127.0.0.1:9999", $errno, $errstr, STREAM_SERVER_BIND); if (!$socket) { die("{$errstr} ({$errno})"); } while (1) { $pkt = stream_socket_recvfrom($socket, 65535, 0, $peer); $this->package_decode($pkt); //echo "$peer: $pkt\n"; //stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer); } }
function server_loop() { while (true) { $read_fds = array($this->server_sock); if (stream_select($read_fds, $write = null, $exp = null, null)) { $data = ''; while (true) { $buf = stream_socket_recvfrom($this->server_sock, $this->buffer_size, 0, $peer); $data .= $buf; if ($buf === null or strlen($buf) < $this->buffer_size) { break; } } $this->protocol->onData($peer, $data); } } }
public function listen() { do { $received = stream_socket_recvfrom($this->socket, 33000, 0, $peer); $code = json_decode($received, true); // drop "[".$code['s']."] ". $blacklisted = false; foreach (self::$FILTER as $pattern) { if (preg_match($pattern, $code['d']) > 0) { $blacklisted = true; } } if (!$blacklisted) { $this->render($code); } } while ($received !== false); }
/** * 接收Udp数据 * 如果数据超过一个udp包长,需要业务自己解析包体,判断数据是否全部到达 * @param resource $socket * @param $null_one $flag * @param $null_two $base * @return void */ public function dealBroadcastUdp($socket, $null_one = null, $null_two = null) { $data = stream_socket_recvfrom($socket, self::MAX_UDP_PACKEG_SIZE, 0, $address); // 可能是惊群效应 if (false === $data || empty($address)) { return false; } // 解析包体 $data = json_decode(trim($data), true); if (empty($data)) { return false; } // 无法解析的包 if (empty($data['cmd']) || $data['cmd'] != 'REPORT_IP') { return false; } // 回应 return stream_socket_sendto($this->broadcastSocket, json_encode(array('result' => 'ok')), 0, $address); }
/** * Listen for connections. */ public function run() { while ($this->socket) { // Keep the server always listening. $client = stream_socket_accept($this->socket, -1); if ($client) { echo 'Incoming connection.' . PHP_EOL; $request = stream_socket_recvfrom($client, 2048); if ($request) { echo 'Request: ' . PHP_EOL . $request; // Send the handshake. stream_socket_sendto($client, $this->dohandshake($request)); // And send the information requested. // @todo: fetch the information based on the getResource(). stream_socket_sendto($client, "<xml>Hey human</xml>"); } // And close the client. fclose($client); } else { exit; } } }
/** * 处理udp连接(udp其实是无连接的,这里为保证和tcp连接接口一致) * @param resource $socket */ public function acceptUdpConnection($socket) { $recv_buffer = stream_socket_recvfrom($socket, self::MAX_UDP_PACKEG_SIZE, 0, $remote_address); if (false === $recv_buffer || empty($remote_address)) { return false; } // 模拟一个连接对象 $connection = new UdpConnection($socket, $remote_address); if ($this->onMessage) { if ($this->_protocol) { $parser = $this->_protocol; $recv_buffer = $parser::decode($recv_buffer, $connection); } ConnectionInterface::$statistics['total_request']++; try { call_user_func($this->onMessage, $connection, $recv_buffer); } catch (Exception $e) { ConnectionInterface::$statistics['throw_exception']++; } } }
/** * Gets bytes from this socket without incrementing the read position * * Subsequent calls to read from this socket will return the same bytes. * Peek can block just like read if the socket is not ready to be read. * * The data returned is raw data. For encytpted sockets, the encrypted * bytes are returned. This is unlike the behaviour of * {@link Net_Notifier_Socket_Abstract::read()}, which returnes unencrypted * data. * * @param integer $length the maximum number of bytes to read. * * @return string up to <kbd>$length</kbd> bytes or data from this socket. */ public function peek($length) { return stream_socket_recvfrom($this->socket, $length, STREAM_PEEK); }
/** * 处理受到的数据 * @param event_buffer $event_buffer * @param int $fd * @return void */ public function dealInputBase($connection, $flag, $fd = null) { $this->currentDealFd = $fd; $buffer = stream_socket_recvfrom($connection, $this->recvBuffers[$fd]['remain_len']); // 出错了 if ('' == $buffer && '' == ($buffer = fread($connection, $this->recvBuffers[$fd]['remain_len']))) { if (!feof($connection)) { return; } // 客户端提前断开链接 $this->statusInfo['client_close']++; // 如果该链接对应的buffer有数据,说明发生错误 if (!empty($this->recvBuffers[$fd]['buf'])) { $this->notice("CLIENT_CLOSE\nCLIENT_IP:" . $this->getRemoteIp() . "\nBUFFER:[" . var_export($this->recvBuffers[$fd]['buf'], true) . "]\n"); } // 关闭链接 $this->closeClient($fd); if ($this->workerStatus == self::STATUS_SHUTDOWN) { $this->stop(); } return; } $this->recvBuffers[$fd]['buf'] .= $buffer; $remain_len = $this->dealInput($this->recvBuffers[$fd]['buf']); // 包接收完毕 if (0 === $remain_len) { // 执行处理 try { // 业务处理 $this->dealProcess($this->recvBuffers[$fd]['buf']); } catch (\Exception $e) { $this->notice('CODE:' . $e->getCode() . ' MESSAGE:' . $e->getMessage() . "\n" . $e->getTraceAsString() . "\nCLIENT_IP:" . $this->getRemoteIp() . "\nBUFFER:[" . var_export($this->recvBuffers[$fd]['buf'], true) . "]\n"); $this->statusInfo['throw_exception']++; $this->sendToClient($e->getMessage()); } // 是否是长连接 if ($this->isPersistentConnection) { // 清空缓冲buffer $this->recvBuffers[$fd] = array('buf' => '', 'remain_len' => $this->prereadLength); } else { // 关闭链接 if (empty($this->sendBuffers[$fd])) { $this->closeClient($fd); } } } else { if (false === $remain_len) { // 出错 $this->statusInfo['packet_err']++; $this->sendToClient('packet_err:' . $this->recvBuffers[$fd]['buf']); $this->notice("PACKET_ERROR\nCLIENT_IP:" . $this->getRemoteIp() . "\nBUFFER:[" . var_export($this->recvBuffers[$fd]['buf'], true) . "]\n"); $this->closeClient($fd); } else { $this->recvBuffers[$fd]['remain_len'] = $remain_len; } } // 检查是否是关闭状态或者是否到达请求上限 if ($this->workerStatus == self::STATUS_SHUTDOWN || $this->statusInfo['total_request'] >= $this->maxRequests) { // 停止服务 $this->stop(); // EXIT_WAIT_TIME秒后退出进程 pcntl_alarm(self::EXIT_WAIT_TIME); } }
set_time_limit(0); // connecting to database $db = new mysql(DB_HOST, '', DB_USER, DB_PASSWORD, DB_NAME); include_once "./load_settings.php"; include_once DIR_MODULES . "control_modules/control_modules.class.php"; // ... set_time_limit(0); include_once DIR_MODULES . 'snmpdevices/snmpdevices.class.php'; $snmpdevices = new snmpdevices(); $socket = stream_socket_server("udp://0.0.0.0:162", $errno, $errstr, STREAM_SERVER_BIND); // If we could not bind successfully, let's throw an error if (!$socket) { die($errstr); } else { do { $pkt = stream_socket_recvfrom($socket, 512, 0, $peer); if (preg_match('/:\\d+$/', $peer, $m)) { $peer = str_replace($m[0], '', $peer); } echo date('Y-m-d H:i:s') . ' new snmp trap from ' . $peer . "\n"; $device = SQLSelectOne("SELECT ID FROM snmpdevices WHERE HOST LIKE '" . DBSafe($peer) . "'"); if ($device['ID']) { $snmpdevices->readDevice($device['ID']); } else { $device['TITLE'] = $peer; $device['HOST'] = $peer; $device['ID'] = SQLInsert('snmpdevices', $device); } } while ($pkt !== false); } $db->Disconnect();
/** * Listen to all the created sockets and return the responses * * @return array */ protected function sockets_listen() { // Set the loop to active $loop_active = TRUE; // To store the responses $responses = array(); // To store the sockets $sockets = array(); // Loop and pull out all the actual sockets we need to listen on foreach ($this->sockets as $socket_id => $socket_data) { // Append the actual socket we are listening to $sockets[$socket_id] = $socket_data['socket']; } // Init some variables $read = $sockets; $write = NULL; $except = NULL; // Check to see if $read is empty, if so stream_select() will throw a warning if (empty($read)) { return $responses; } // This is when it should stop $time_stop = microtime(TRUE) + $this->timeout; // Let's loop until we break something. while ($loop_active && microtime(TRUE) < $time_stop) { // Now lets listen for some streams, but do not cross the streams! $streams = stream_select($read, $write, $except, 0, $this->stream_timeout); // We had error or no streams left, kill the loop if ($streams === FALSE || $streams <= 0) { $loop_active = FALSE; break; } // Loop the sockets that received data back foreach ($read as $socket) { // See if we have a response if (($response = stream_socket_recvfrom($socket, 8192)) === FALSE) { continue; // No response yet so lets continue. } // Check to see if the response is empty, if so we are done // @todo: Verify that this does not affect other protocols, added for Minequery // Initial testing showed this change did not affect any of the other protocols if (strlen($response) == 0) { // End the while loop $loop_active = FALSE; break; } // Add the response we got back $responses[(int) $socket][] = $response; } // Because stream_select modifies read we need to reset it each // time to the original array of sockets $read = $sockets; } // Free up some memory unset($streams, $read, $write, $except, $sockets, $time_stop, $response); return $responses; }