/** * Execute the action. * @param array command line parameters specific for this command */ public function run($args) { // set some variables //$host = "127.0.0.1"; $host = "192.168.1.2"; $port = 4122; //$icounter=0; /* // don't timeout! set_time_limit(0); // create socket $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); // bind socket to port $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); $icounter=0; while ($icounter < 3) { // start listening for connections $result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); // accept incoming connections // spawn another socket to handle communication $spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); // read client input $input = socket_read($spawn, 1024) or die("Could not read input\n"); $handle = fopen("d:\\resource.txt", "a+"); fwrite($handle,$input); /* $imei_ary = array(); foreach (str_split($input) as $chr) $imei_ary[] = sprintf("%c", ord($chr)); */ /* $input = '#RD000001004361412111849153955.6583N03253.2103E000.04500000A00113971Da7LARNU8H40GT20KHU0W000296B15CE086'; echo $input; */ // Create the server try { $server = new Socket(); } catch (SocketException $e) { echo "Can't start server, " . $e->getMessage(); } // Start the listen loop try { $server->listen($host, $port); } catch (SocketException $e) { echo "Can't listen, " . $e->getMessage(); } /* $input = '#SE00000100454355543020162426015'; */ }
public static function shutdownApplicationServer() { self::$clientClassesLoader && ClassLoader::removeLoader(self::$clientClassesLoader); // Send shutdown message (this is not supported by live servers // but functionality added via EascMessageFactory::setHandler()) try { $s = new Socket(self::$bindAddress[0], self::$bindAddress[1]); $s->connect(); $s->write(pack('Nc4Na*', DEFAULT_PROTOCOL_MAGIC_NUMBER, 1, 0, 61, FALSE, 0, NULL)); $s->close(); } catch (Throwable $e) { // Fall through, below should terminate the process anyway } $status = self::$serverProcess->out->readLine(); if (!strlen($status) || '+' != $status[0]) { while ($l = self::$serverProcess->out->readLine()) { $status .= $l; } while ($l = self::$serverProcess->err->readLine()) { $status .= $l; } self::$serverProcess->close(); throw new IllegalStateException($status); } self::$serverProcess->close(); }
/** * @expectedException Phanglia\ConnectionException */ public function testConnectionProblem() { $socket = new Socket('-_/#$*&!)@&#$', 32132, []); $socket->send('some_payload'); $this->assertTrue($socket->isOpen()); $socket->close(); $this->assertFalse($socket->isOpen()); }
/** * Creates a new SocketException. * * @param string message * @param Socket socket class */ public function __construct($message, Socket $socket) { $this->errorNumber = $socket->last_error(); $this->errorDesc = $socket->get_error(); $this->socketAddress = $socket->bind_address; $this->socketPort = $socket->bind_port; $this->socket = $socket; parent::__construct($message, $this->errorNumber); }
/** * @param Socket $socket * * @return bool */ public function equals(Socket $socket) : bool { if (!$socket instanceof $this) { return FALSE; } if ($this->getFileName() != $socket->getFileName()) { return FALSE; } return TRUE; }
/** * Write the Request Header * <req_len> + <req_type> + <topic_len> + <topic> + <partition> * * @param Socket $socket Socket * * @return void */ protected function writeRequestHeader(Socket $socket) { // REQUEST_LENGTH (int) + REQUEST_TYPE (short) $socket->write(pack('N', $this->sizeInBytes() + 2)); $socket->write(pack('n', $this->id)); // TOPIC_SIZE (short) + TOPIC (bytes) $socket->write(pack('n', strlen($this->topic)) . $this->topic); // PARTITION (int) $socket->write(pack('N', $this->partition)); }
public function flush() { $this->socket->open(); $metrics = array_map(function (MetricInterface $metric) { return $metric->getData(); }, $this->queue); $packets = $this->fillPackets($metrics); foreach ($packets as $packet) { $this->socket->write($packet); } $this->queue = []; $this->socket->close(); }
/** * ClientSocket constructor */ public function __construct($addr) { parent::__construct(); $this->address = $addr; $proto = strtolower(strtok($addr, ":")); $s = strtok(""); if ($proto === "udp" || $proto === "unix") { $this->real_address = $addr; } else { $this->real_address = "tcp:" . $s; if ($proto != "tcp") { switch ($proto) { case "ssl": $this->crypto_type = STREAM_CRYPTO_METHOD_SSLv23_CLIENT; break; case "tls": $this->crypto_type = STREAM_CRYPTO_METHOD_TLS_CLIENT; break; case "sslv2": $this->crypto_type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT; break; case "sslv3": $this->crypto_type = STREAM_CRYPTO_METHOD_SSLv3_CLIENT; break; default: if (defined($cname = "STREAM_CRYPTO_METHOD_" . strtoupper($proto) . "_CLIENT")) { $this->crypto_type = constant($cname); } } } } }
/** * ServerSocket constructor */ public function __construct($addr) { parent::__construct(); $this->address = $addr; $proto = strtolower(strtok($addr, ":")); if ($proto === "udp" || $proto === "unix") { $this->real_address = $addr; } else { $this->real_address = "tcp:" . strtok(""); if ($proto !== "tcp") { switch ($proto) { case "ssl": $this->crypto_type = STREAM_CRYPTO_METHOD_SSLv23_SERVER; break; case "tls": $this->crypto_type = STREAM_CRYPTO_METHOD_TLS_SERVER; break; case "sslv2": $this->crypto_type = STREAM_CRYPTO_METHOD_SSLv2_SERVER; break; case "sslv3": $this->crypto_type = STREAM_CRYPTO_METHOD_SSLv3_SERVER; break; default: if (defined($cname = "STREAM_CRYPTO_METHOD_" . strtoupper($proto) . "_SERVER")) { $this->crypto_type = constant($cname); } else { throw new ServerException("unknown transport/crypto type '{$proto}'"); } } } } }
public function __construct($url) { if (extension_loaded('curl')) { //实例化curl类 $curl = new Curl('get', $url); //TODO可以用Regiter去保存 $this->output = $curl->output; } else { //实例化Socket类 并传入url和设置超时时常 $socket = new Socket($url, 10); //调用getMethod去模拟GET请求 $socket->getMethod(); //获取响应body $this->output = $socket->getResponseBody(); } }
public function __construct($host = 'localhost', $port = 8000, $ssl = false) { parent::__construct($host, $port, $ssl); $this->log('Server created'); $this->_host = $host; $this->_port = $port; }
/** * Attempts to notify the server of targetUri that sourceUri refers to it. * * @param object Controller object */ public function trackbackUrl($sourceUri, $targetUri) { $urlData = $this->Socket->get($targetUri); $trackbackServerUri = $this->_determineTrackbackUri($this->Socket->response); if (!empty($trackbackServerUri)) { $response = $this->Socket->post($targetUri, $data); } }
/** * @desc 打开套接字,设置为非阻塞 * @see Socket::Open() */ public function Open($sAddr = "0.0.0.0", $iPort = 0, $bReuseAddr = true) { if (parent::Open($sAddr, $iPort, $bReuseAddr) == -1 || $this->SetBlock(false) == -1) { $this->Close(); return -1; } return 0; }
/** * Disconnect all the Clients and shut down the server. * * @return void */ private function shutDownEverything() { foreach ($this->clients as $client) { $this->disconnect($client); } $this->masterSocket->close(); unset($this->hooks, $this->address, $this->port, $this->timeout, $this->domain, $this->masterSocket, $this->maxClients, $this->maxRead, $this->clients, $this->readType); }
public function testShutdown() { Socket::create()->setHost('localhost')->setPort(80)->close(); $timedOutSocket = Socket::create()->setHost('google.com')->setPort(80)->setTimeout(1)->connect(); $timedOutSocket->write("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n"); $timedOutSocket->read(256); $timedOutSocket->close(); $this->assertEquals(42, 42); }
/** * socket遠程連接 * @author wave */ protected static function connect() { if (empty(self::$link)) { Socket::create(); if (!socket_connect(self::$sock, self::$address, self::$port)) { exit(socket_strerror(socket_last_error())); } ++self::$link; } }
/** * Request information realtime. * * The data that are you requesting (for instance, what is in $mSearch) will not be parsed by the bot. * This essentially means it is the job of the code using that request to deal with parsing it properly. * * <code>$aMatches = $this->getRealtimeRequest("NAMES #westie", array(353, 366), 4); * * // Array * // ( * // [0] => :ircd 353 OUTRAGEbot = #westie :OUTRAGEbot ~Westie * // [1] => :ircd 366 OUTRAGEbot #westie :End of /NAMES list. * // )</code> * * @param string $sRequest Message to send to the server. * @param mixed $mSearch IRC numerics to cache. * @param integer $iSleep <i>Microseconds</i> to sleep before getting input. * @return array The response matched to the data in $aSearch. */ public function getRealtimeRequest($sRequest, $mSearch, $iSleep = 10000) { $this->oCurrentBot->iUseQueue = true; $this->oCurrentBot->aSearch = (array) $mSearch; $this->oCurrentBot->aMatchQueue = array(); $this->oCurrentBot->Output($sRequest); usleep($iSleep); $this->oCurrentBot->Input(); $this->oCurrentBot->iUseQueue = false; return $this->oCurrentBot->aMatchQueue; }
/** * Process events on the master socket ($this->socket) * * @return void */ protected function processMasterSocket() { $new = null; try { $new = $this->socket->accept(); } catch (Exception $e) { $this->server->log('Socket error: ' . $e, 'err'); return; } $connection = $this->createConnection($new); $this->server->notify(Server::EVENT_SOCKET_CONNECT, array($new, $connection)); }
public static function shutdownServer() { // Tell the server to shut down try { $c = new Socket(self::$bindAddress[0], self::$bindAddress[1]); $c->connect(); $c->write("HALT\n"); $c->close(); } catch (Throwable $ignored) { // Fall through, below should terminate the process anyway } $status = self::$serverProcess->out->readLine(); if (!strlen($status) || '+' != $status[0]) { while ($l = self::$serverProcess->out->readLine()) { $status .= $l; } while ($l = self::$serverProcess->err->readLine()) { $status .= $l; } self::$serverProcess->close(); throw new IllegalStateException($status); } self::$serverProcess->close(); }
/** * Forces the server to refresh its configuration. * * @since 5.1 * @return string Server result string. */ public function refresh() { try { $result = ''; $auth = ModuleServerAuthenticator::instance('ModuleServerAuthenticator'); $this->socket->connect($this->host, $this->port); $request = 'REFRESH Module/1.0' . "\r\n"; $request .= 'User: admin' . "\r\n"; $request .= 'Password: '******'admin') . "\r\n"; $this->socket->write($request); $result = $this->socket->readAll(); $this->socket->disconnect(); } catch (\Innomatic\Net\Socket\SocketException $e) { $result = 'Module server is down.' . "\n"; } return $result; }
function read() { if (!$this->connected) { $this->connect(); } else { $result = socket_read($this->socket, $this->read_buffer->space_remaining()); if ($result === FALSE) { throw new SocketException("Error reading from {$this->name} ({$this->address}:{$this->port})", $this->socket); } elseif ($result === '') { $this->log("marking as disconnected" . Socket::str_error($this->socket) . "\n"); $this->disconnect(); } else { $this->read_buffer->append($result); // $this->log("Read:\n" . hex_pretty_print($result) . "\n"); } } }
/** * force the ModuleServiceSocketHandler to refresh the registry * * @since 5.1 */ protected function force_refresh() { print "force_refresh" . "\n"; $request = ''; $address = '127.0.0.1'; $context = \Innomatic\Module\Server\ModuleServerContext::instance('\\Innomatic\\Module\\Server\\ModuleServerContext'); try { $port = $context->getConfig()->getKey('service_port'); $this->socket->connect($address, $port); $request = 'REFRESH Module/1.1' . "\r\n"; $request .= 'User: admin' . "\r\n"; $request .= 'Password: '******'admin') . "\r\n"; $this->socket->write($request); $result = $this->socket->readAll(); $this->socket->disconnect(); } catch (\Innomatic\Net\Socket\SocketException $e) { print "Cannot refresh: server " . $address . ":" . $port . " down!" . "\n"; } print $result; }
/** * 發送EMAIL的組件 * @param Array $opt 發送的數據 * @author wave */ public function mail_send($opt = array()) { set_time_limit(0); Socket::$address = $opt['address']; Socket::$port = $opt['port']; $_data = array(0 => "EHLO " . $opt['cc'] . "\r\n", 1 => "AUTH LOGIN\r\n", 2 => base64_encode($opt['form']) . "\r\n", 3 => base64_encode($opt['pass']) . "\r\n", 4 => "MAIL FROM: <" . $opt['form'] . ">\r\n", 5 => "RCPT TO: <" . $opt['to'] . ">\r\n", 6 => "Content-Type: text/html; charset=\"utf-8\"\r\n", 7 => "DATA\r\n", 8 => "Form: " . $opt['cc'] . "<" . $opt['form'] . ">\r\nTo: " . $opt['to'] . "\r\nSubject: " . $opt['title'] . "\r\n\r\n" . $opt['body'] . "\r\n", 9 => "\r\n.\r\n", 10 => "QUIT\r\n"); $jilu = array(); //記錄發送數組 foreach ($_data as $k => $v) { Socket::$data = $v; Socket::send(); $jilu['ok'][$k] = Socket::read(); if (!in_array($k, array(7, 8))) { } if ($k - count($_data) == 0) { if (substr(Socket::read(), 0, 3) != "250") { $jilu['err'] = Socket::read(); } } } Socket::colse(); return isset($jilu['err']) ? $jilu['err'] : 'ok'; }
/** * IPC Socket constructor * * @param resource $fd * @param int $pid */ public function __construct($fd, $pid = false) { parent::__construct($fd); $this->Set_Write_Buffer(self::IPC_MAX_PACKET_SIZE); $this->pid = $pid; }
/** * * @param unknown $iddevice * @param unknown $optionid * @param unknown $val */ function mcTemperature($iddevice, $optionid, $val) { $socket = new Socket(); $data = array('room_device_id' => $iddevice, 'option_id' => $optionid, 'value' => $val); $socket->send('send_to_device', $data); }
/** * Send messages to Kafka * * @param array $messages Messages to send * @param string $topic Topic * @param integer $partition Partition * * @return boolean */ public function send(array $messages, $topic, $partition = 0xffffffff) { $this->connect(); return $this->socket->write(Encoder::encode_produce_request($topic, $partition, $messages, $this->compression)); }
function knx_read($daemon, $addr) { $socket = new Socket(); $tab = array('daemon' => $daemon, 'addr' => $addr); $socket->send('knx_read', $tab); }
/** * get broker broker connect * * @param string $host * @param null $lockKey * * @return array * @access private */ public function getStream($host, $lockKey = null) { if (!$lockKey) { $lockKey = uniqid($host); } list($hostname, $port) = explode(':', $host); // find unlock stream if (isset(self::$stream[$host])) { foreach (self::$stream[$host] as $key => $info) { if ($info['locked']) { continue; } else { self::$stream[$host][$key]['locked'] = true; $info['stream']->connect(); return array('key' => $key, 'stream' => $info['stream']); } } } // no idle stream $stream = new Socket($hostname, $port, $this->getStreamOption('RecvTimeoutSec'), $this->getStreamOption('RecvTimeoutUsec'), $this->getStreamOption('SendTimeoutSec'), $this->getStreamOption('SendTimeoutUsec')); $stream->connect(); self::$stream[$host][$lockKey] = array('locked' => true, 'stream' => $stream); return array('key' => $lockKey, 'stream' => $stream); }
public static function synchronizeInboundAltitude(IConnection $connect, $syncID, $userID) { global $database, $servers_altitude; $response = ""; $path_data = PATHDATA_SOCKET_EASYLOAD; $path_file = "{$path_data}/{$userID}_{$syncID}"; $output = ""; try { //$objCampaign = Campaign::getCampaignByID($connect, $campaignID); //$shortname = $objCampaign->getShortName(); //$objSync = new SynchronizeFolio($syncID,0, 0, "", "", ""); $without_easycode = FolioImport::getRegistersInboundRegestion($connect, 'S'); $action = 1; try { $objSocket = new Socket(IP_SOCKET_EASYLOAD, PORT_SOCKET_EASYLOAD, TIMEOUT_SOCKET_EASYLOAD); $objSocket->connect(); // 1. Comprobando enlace con socket $objSocket->send("ACTION=TEST"); $response = $objSocket->receive(); //$objSync->updateSynchronizeAction($connect, $action, "OK"); // 2. Generando archivo .TYP $action = 2; sleep(1); $filename = Util::generateFilesImportInbound($connect, $path_file, "TYP", true); //$objSync->updateSynchronizeAction($connect, $action, "OK"); // 3. Generando archivo .dat $action = 3; sleep(1); Util::generateFilesImportInbound($connect, $path_file, "DAT", true); //$objSync->updateSynchronizeAction($connect, $action, "OK"); // 4. Delegar a socket importar data en altitude $action = 4; sleep(1); $serverAtt = SERVER_NORMAL; //trim($objCampaign->getServerAltitude()) == "" ? SERVER_NORMAL : trim($objCampaign->getServerAltitude()); $connectSQL = Util::createConnection(ENGINE_SQLSERVER, $database[$servers_altitude["{$serverAtt}"]['altitude']]); $connectSQL->connect(); $rsDataAltitude = Altitude::getCampaignsByContactTable($connectSQL, 'outbound_retencion'); $data = $connectSQL->getRows($rsDataAltitude); $campaignATT = trim($data['shortname']); $accessInstance = $database[$servers_altitude["{$serverAtt}"]['altitude']]; $instance = $accessInstance['serverIA'] . ":" . $accessInstance['portIA']; $objSocket->send("ACTION=IMPORT;CAMPAIGN={$campaignATT};FILE={$filename};INSTANCE={$instance};USER={$userID};SYNCID={$syncID}"); $response = $objSocket->receive(); echo $response; /*if ($response == "ERROR" || $response == "WARN") { $msg = Util::getContentFile("{$path_file}/{$campaignATT}_messages.txt"); $txt = "Ocurrio un problema en la importacion altitude"; $mex = new MyException("$msg", 0, $txt); $mex->publisherSqlException(false); $mex->setText("{$txt}. Error# {$mex->getExceptionID()}"); $output = "{$txt}. Error# {$mex->getExceptionID()}."; if ($response == "ERROR") { throw $mex; } }*/ //$objSync->updateSynchronizeAction($connect, $action, "{$response}"); // 5. Finalizando enlace con socket $action = 5; $objSocket->changeTimeout(15); $objSocket->send("ACTION=END"); $response = $objSocket->receive(); //$objCampaign = Campaign::getCampaignByID($connect, $campaignID); //$objFolio = FolioImport::getFolioImport($connect, $folioID); //$total_folio = $objFolio->getRegistersImported(); //$without_easycode = FolioImport::getRegistersWithoutEasycode($connect, $shortname, $folioID, 'S'); //$objSync->updateSynchronizeAction($connect, $action, $total_folio - $without_easycode); } catch (MyException $ex) { $output = "ERROR: " . $ex->getText(); //$objSync->updateSynchronizeAction($connect, $action, "ERROR: {$ex->getText()}"); } } catch (MyException $ex) { $output = "Error: " . $ex->getText(); } return $output; }
/** * This method will call the onClose method which will call this method in all * observing objects. After that, the TCP connection will be closed. * Use the disconnect() method if you want to close the WebSocket Connection cleanly * * @param int $nReason The status code or reason for the close * @param string $sReason The status code or reason for the close as text * @return boolean True on succes, false otherwise */ public function close($nReason = null, $sReason = null) { /* Update the readystate */ $this->m_nReadyState = static::STATE_CLOSED; /* Raise events */ $this->onClose($nReason, $sReason); /* This connection is not in CONNECTING state anymore */ unset(static::$aInConnectingState[$this->m_sIp]); /* Call the parent close function to close the TCP connection */ return parent::close(); }