function http_request($host, $data) { if (!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { echo "socket_create() error!\r\n"; exit; } if (!socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1)) { echo "socket_set_option() error!\r\n"; exit; } if (!socket_connect($socket, $host, 80)) { echo "socket_connect() error!\r\n"; exit; } if (!socket_write($socket, $data, strlen($data))) { echo "socket_write() errror!\r\n"; exit; } while ($get = socket_read($socket, 1024, PHP_NORMAL_READ)) { $content .= $get; } socket_close($socket); $array = array('HTTP/1.1 404 Not Found', 'HTTP/1.1 300 Multiple Choices', 'HTTP/1.1 301 Moved Permanently', 'HTTP/1.1 302 Found', 'HTTP/1.1 304 Not Modified', 'HTTP/1.1 400 Bad Request', 'HTTP/1.1 401 Unauthorized', 'HTTP/1.1 402 Payment Required', 'HTTP/1.1 403 Forbidden', 'HTTP/1.1 405 Method Not Allowed', 'HTTP/1.1 406 Not Acceptable', 'HTTP/1.1 407 Proxy Authentication Required', 'HTTP/1.1 408 Request Timeout', 'HTTP/1.1 409 Conflict', 'HTTP/1.1 410 Gone', 'HTTP/1.1 411 Length Required', 'HTTP/1.1 412 Precondition Failed', 'HTTP/1.1 413 Request Entity Too Large', 'HTTP/1.1 414 Request-URI Too Long', 'HTTP/1.1 415 Unsupported Media Type', 'HTTP/1.1 416 Request Range Not Satisfiable', 'HTTP/1.1 417 Expectation Failed', 'HTTP/1.1 Retry With'); for ($i = 0; $i <= count($array); $i++) { if (eregi($array[$i], $content)) { return "{$array[$i]}\r\n"; break; } else { return "{$content}\r\n"; break; } } }
/** * {@inheritdoc} */ public function flushAll() { if ($this->currentOnly) { return apc_clear_cache('user') && apc_clear_cache(); } $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip'])) == 3) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl()); $command .= sprintf("Host: %s\r\n", $server['domain']); if ($server['basic']) { $command .= sprintf("Authorization: Basic %s\r\n", $server['basic']); } $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = ''; do { $buffer = socket_read($socket, 1024); $content .= $buffer; } while (!empty($buffer)); if ($result) { $result = substr($content, -2) == 'ok'; } } return $result; }
function sock_write(&$sock, $data, $length = 0, $flush = false) { $sock->error = ""; $sock->errno = 0; if (empty($length)) { $length = strlen($data); } $ret = false; $retries = 5; while (($ret === false || $ret < $length) && $retries > 0) { $ret += @socket_write($sock->socket, substr($data, $ret), $length - $ret); if ($ret === false || $ret < $length) { usleep(500); } $retries--; } if ($ret === false || $ret < $length) { $sock->errno = 0; if ($ret < $length && $ret !== false) { $sock->error = "Socket write timeout"; } else { $sock->error = "Socket write error"; } } /* else if ($flush) sock_flush($sock);*/ }
public function send($cmd) { if ($this->getSocket()) { socket_write($this->getSocket(), $cmd, strlen($cmd)); flush(); } }
private static function _tcp_send_request($socket_write_json = null) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (false === $sock) { echo "sock create error!\n"; } $address = Config::get("kgi.kgi_mid_server_ip"); $port = Config::get("kgi.kgi_mid_server_port"); try { $result = socket_connect($sock, $address, $port); if ($result === false) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($sock)) . "\n"; exit; die; } socket_write($sock, $socket_write_json, strlen($socket_write_json)); while ($out_str = socket_read($sock, 2048)) { // echo "revice result\n"; // echo $out_str . "\n"; $json_data = json_decode($out_str); break; } socket_close($sock); } catch (\ErrorException $e) { //echo $e->getMessage() . "\n"; } }
public function sendHeartbeat($sock) { global $listenport; global $MASTERPASSWORD; $msg = "\\heartbeat\\port\\{$listenport}\\gamename\\master\\password\\{$MASTERPASSWORD}\\final\\"; @socket_write($sock, $msg); }
public function BroadCastMessage($Message) { $str = json_encode($Message) . "#"; foreach ($this->clients as $client) { socket_write($client, $str, strlen($str)); } }
function perform_handshaking($receved_header, $client_conn, $host, $port) { //se crea un arreglo para guardar los datos enviados del cliente $headers = array(); //divide el contenido enviado por el cliente en array,por medio de la expresion regular //crea los array apartir el retorno de carro (\r) y salto de linea (\n). $lines = preg_split("/\r\n/", $receved_header); //recorre el arreglo LINES para meterlo en el arreglo HEADERS foreach ($lines as $line) { $line = chop($line); //elimina los espacios en blanco //Aqui se crea un arreglo matches donde se anexara al arreglo HEADERS donde el indicide de //headers tendra el valor de maches[1] y su valor sera el de matches[2] if (preg_match('/\\A(\\S+): (.*)\\z/', $line, $matches)) { $headers[$matches[1]] = $matches[2]; } } $secKey = $headers['Sec-WebSocket-Key']; // se obtiene el balor de Sec-WebSocket-Key //genera el encriptado base64 para responder al cliente //sha1 calcula el has del string //pack empaqueta el sha1 a una cadena binaria donde H* indica que debe ser todo el texto //en cadena hexadecimal. //base64_encode codifica el paquete binario en base64 $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); //hand shaking header -- Crea el mensaje para el cliente y se extablesca la conexion $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" . "Upgrade: websocket\r\n" . "Connection: Upgrade\r\n" . "WebSocket-Origin: {$host}\r\n" . "WebSocket-Location: ws://{$host}:{$port}/servidor.php\r\n" . "Sec-WebSocket-Accept:{$secAccept}\r\n\r\n"; //envia al cliente la respuesta para establecer la comunicacion entre cliente y socket socket_write($client_conn, $upgrade, strlen($upgrade)); }
public function write($body) { $this->updateStatus(); if ($this->writable) { socket_write($this->_socket, $body, strlen($body)); } }
public function flushAll() { $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip']) == 3)) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->router->generate('sonata_page_apc_cache', array('token' => $this->token))); $command .= sprintf("Host: %s\r\n", $server['domain']); $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = socket_read($socket, 1024); if ($result) { $result = substr($content, -2) == 'ok' ? true : false; } } return $result; }
/** * send summary to graphite * @return bool - status of operation (TRUE = success, FALSE = failure) */ public function sendAll() { $bucket_prefix = $this->buildBucketPrefix(); $address = gethostbyname($this->cfg['host']); $cmdBuf = ''; foreach ($this->stats_summary as $stat) { // action name mapping $action = preg_replace('/[\\. ]/', '', $stat['action']); $action = preg_replace('/_ACTION$/', '', $action); // HACK to prevent old event names to appear in graphite if (!preg_match('/_/', $action)) { continue; } $cmdBuf .= $bucket_prefix . $action . ' ' . $stat['value'] . ' ' . $stat['time'] . "\n"; } // var_dump($cmdBuf); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $result = socket_connect($socket, $address, $this->cfg['port']); if (!$result) { return false; } $write_result = socket_write($socket, $cmdBuf, strlen($cmdBuf)); if (!$write_result) { return false; } return true; }
function query($query_string, $timeout) { $tmp = ""; $string = ""; $stime = array(); $this->timer($stime); $n = strlen($query_string); if ($this->is_connected == 0) { $this->reconnect(); } if ($this->sock && $n > 0 && socket_write($this->sock, $query_string, $n) == $n) { while (1) { if ($tmp = socket_read($this->sock, 81920, PHP_BINARY_READ)) { if (($n = strpos($tmp, SOCK_END)) === FALSE) { $string .= $tmp; } else { $string .= substr($tmp, 0, $n + strlen(SOCK_END)); break; } } else { $this->close(); return false; } $usec = $this->timer($stime); if ($usec >= $timeout) { $this->close(); return false; } usleep(1); } return $string; } $this->close(); return false; }
/** * Write data to socket * * @param $data * * @throws Exception\IO\ReadException */ function write($data) { if (!socket_write($this->socketResource, $data, strlen($data))) { throw new WriteException($this, $data); } $this->getEventDispatcher()->dispatch(WriteEvent::getEventName(), new WriteEvent($this, $data)); }
private function await() { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($sock < 0) { echo "Error:" . socket_strerror(socket_last_error()) . "\n"; } $ret = socket_bind($sock, $this->ip, $this->port); if (!$ret) { echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "\n"; exit; } echo "OK\n"; $ret = socket_listen($sock); if ($ret < 0) { echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "\n"; } do { $new_sock = null; try { $new_sock = socket_accept($sock); } catch (Exception $e) { echo $e->getMessage(); echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "\n"; } try { $request_string = socket_read($new_sock, 1024); $response = $this->output($request_string); socket_write($new_sock, $response); socket_close($new_sock); } catch (Exception $e) { echo $e->getMessage(); echo "READ FAILED:" . socket_strerror(socket_last_error()) . "\n"; } } while (TRUE); }
public function send($data) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket == null) { return false; } socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $this->timeout, 'usec' => 0)); if (!socket_connect($socket, $this->host, $this->port)) { return false; } $packed = json_encode($data); echo $packed; //Write Header socket_write($socket, "ZBXD"); //Write Data length $length = strlen($packed); socket_write($socket, pack("V*", $length, $length >> 32)); socket_write($socket, $packed); $return_header = socket_read($socket, 5); $return_length = unpack("V*", socket_read($socket, 8)); $return_length = $return_length[1] + ($return_length[2] << 32); $return_data = socket_read($socket, $return_length); $return_data = json_decode($return_data); socket_close($socket); return $return_data; }
function refresh_user($discord_id) { global $socket, $error; $so = socket_create(AF_UNIX, SOCK_DGRAM, 0); if ($so === false) { $msg = socket_strerror(socket_last_error()); $error = "Socket failed: {$msg}"; } else { $res = socket_connect($so, $socket); if ($res === false) { $msg = socket_strerror(socket_last_error()); $error = "Connect failed: {$msg}"; } else { $payload = json_encode(array('action' => 'refresh', 'user_id' => $discord_id)); $res = socket_write($so, $payload); if ($res === false) { $error = "Socket send failed"; } else { if ($res < strlen($payload)) { $error = "Socket did not send all data"; } } socket_shutdown($so); socket_close($so); } } }
public function run() { $ret = array(); while (true) { $inArr = $this->get_files_by_ext($this->urlFilePath, 'url'); if (!empty($inArr)) { sleep(2); foreach ($inArr as $in) { if (!in_array($in, $ret)) { $ret[] = $in; exec("cp {$this->urlFilePath}{$in} {$this->backupFilePath}"); $fileContent = file_get_contents($this->urlFilePath . $in); if (socket_write($this->socket, $fileContent, strlen($fileContent))) { $this->addLog("发送到服务器信息成功!发送的内容为: {$fileContent}"); sleep(2); } else { $this->addLog("发送失败! reason :" . socket_strerror($this->socket)); } } } } else { $this->addLog("无URL文件"); sleep(1); } } }
/** * Send message package to the socket server * Basic layer method * * @return mixed */ public function send($msg, $is_block = false) { if (!$this->host || !$this->port) { throw new Hush_Socket_Exception("Please set server's host and port first"); } /* Create a TCP/IP socket. */ $this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->sock < 0) { echo "socket_create() failed.\nReason: " . socket_strerror($this->sock) . "\n"; } $result = @socket_connect($this->sock, $this->host, $this->port); if ($result < 0) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n"; } if ($is_block) { @socket_set_nonblock($this->sock); } // add suffix for socket msg $msg = trim($msg) . "\r\n"; @socket_write($this->sock, $msg, strlen($msg)); $result = @socket_read($this->sock, 2048); // unserialize data from socket server $result = unserialize(trim($result)); return $result; }
function ft_init($socket, $tbl) { $out = socket_read($socket, 2048); echo $out; socket_write($socket, $tbl["team"] . "\n"); $out = socket_read($socket, 2048); echo $out; $tbl = explode("\n", $out); if ($tbl[1]) { $result = array(); $tbl2 = explode(' ', $tbl[1]); $result['x'] = $tbl2[0]; $result['y'] = $tbl2[1]; $map = array(); for ($y = 0; $y < $result['y']; $y++) { $map[$y] = array(); for ($x = 0; $x < $result['x']; $x++) { $map[$y][$x] = 0; } } $map["size"] = $result; return $map; } ft_error("init map", TRUE); }
function Ping($dst_addr, $timeout = 5, $percision = 3) { // lets catch dumb people if ((int) $timeout <= 0) { $timeout = 5; } if ((int) $percision <= 0) { $percision = 3; } // set the timeout socket_set_option($this->icmp_socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $timeout, "usec" => 0)); if ($dst_addr) { if (@socket_connect($this->icmp_socket, $dst_addr, NULL)) { } else { $this->errstr = "Cannot connect to {$dst_addr}"; return FALSE; } $this->Build_Packet(); $this->start_time(); socket_write($this->icmp_socket, $this->request, $this->request_len); if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0)) { $this->time = $this->get_time($percision); return $this->time; } else { $this->errstr = "Timed out"; return FALSE; } } else { $this->errstr = "Destination address not specified"; return FALSE; } }
protected function handleRead($read_sock) { // read until newline or 1024 bytes // socket_read while show errors when the client is disconnected, so silence the error messages $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ); // check if the client is disconnected if ($data === false) { // remove client for $this->clients array $key = array_search($read_sock, $this->clients); unset($this->clients[$key]); echo "client disconnected.\n"; // continue to the next client to read from, if any continue; } // trim off the trailing/beginning white spaces $data = trim($data); // check if there is any data after trimming off the spaces if (!empty($data)) { // send this to all the clients in the $this->clients array (except the first one, which is a listening socket) foreach ($this->clients as $send_sock) { // if its the listening sock or the client that we got the message from, go to the next one in the list if ($send_sock == $this->sock || $send_sock == $read_sock) { continue; } // write the message to the client -- add a newline character to the end of the message socket_write($send_sock, $data . "\n"); } } }
function SendNetwork($h, $str) { global $socketid; $crypted = CryptString($socketid . "|" . $str); socket_write($h, strlen($crypted) . '|' . $crypted); return; }
function run_loop() { //This will stall the thread / request $i = 0; while ($_SESSION['running'] != -1) { #read from local socket and put on session variable while ($out = socket_read($this->socket, 8192)) { if ($out === false) { exit("[Server] Unable to read from local socket"); } $this->met_data .= $out; } #If data on SESSION variable write data to local socket if ($this->handler_data != "") { $in = socket_write($this->socket, $this->handler_data, strlen($this->handler_data)); if ($in === false) { exit("[Server] Unable to write to local socket"); } $this->handler_data = ""; } $this->update_session_data(); if (!stristr(PHP_OS, "linux")) { sleep(1); } //added to work with apache/IIS on windows otherwise the consecutive reads DoS the socket } }
function pole_display_price($label, $price) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (@socket_connect($sock, '127.0.0.1', 1888)) { socket_write($sock, sprintf("\r\n%-19.19s\n\r\$%18.2f ", $label, $price)); } }
function hg_sendCmd($cmd, $ip, $port) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { return false; } $result = socket_connect($socket, $ip, $port); if ($result < 0) { return false; } if (!isset($cmd['charset'])) { $cmd['charset'] = ''; } $str = json_encode($cmd); //echo ($str); //$str = base64_encode($str); socket_write($socket, $str, strlen($str)); $data = ''; while ($out = socket_read($socket, 256)) { $data .= $out; if (strlen($out) < 256) { break; } } socket_close($socket); //$data = base64_decode($data); return $data; }
function ircReport($stuff) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($sock, Settings::pluginGet("host"), Settings::pluginGet("port")); socket_write($sock, $stuff . "\n"); socket_close($sock); }
function sendsock($in) { global $config; $service_port = $config['sockport']; $address = $config['sockhost']; if (!function_exists("socket_create")) { error_log(date("y-m-d H:i:s") . " 未启用socket模块\n", 3, "error.log"); return null; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { error_log(date("y-m-d H:i:s") . "socket_create() failed, reason: " . socket_strerror(socket_last_error()) . "\n", 3, "error.log"); return null; } $result = socket_connect($socket, $address, $service_port); if ($result === false) { error_log(date("y-m-d H:i:s") . "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n", 3, "error.log"); return null; } socket_write($socket, $in, strlen($in)); $result = socket_read($socket, 8192); $arr = unpack("C*", $result); socket_close($socket); return $arr; }
function listenForClients() { $this->serviceConnection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($this->serviceConnection, $this->serviceHost, $this->servicePort); socket_listen($this->serviceConnection, 10); echo 'LISTENING ',$this->servicePort,"\n"; while($clientSocket = socket_accept($this->serviceConnection)) { socket_write($clientSocket, "OK\n"); $deviceToken = trim(socket_read($clientSocket, 512, PHP_NORMAL_READ)); $message = trim(socket_read($clientSocket, 512, PHP_NORMAL_READ)); if(!empty($deviceToken) && !empty($message)) { $this->sendNotification($deviceToken, $message); socket_write($clientSocket, "SENT\n"); } else { socket_write($clientSocket, "ERROR\n"); } socket_close($clientSocket); } }
public function index() { error_reporting(E_ALL); set_time_limit(0); $service_port = 6005; $address = "203.130.45.233"; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n"; } $result = socket_connect($socket, $address, $service_port); if ($result < 0) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n"; } else { echo "连接OK<br>"; } $in = "1!"; //1!是发给这个设备的指令 $out = ''; $out1 = ''; if (!socket_write($socket, $in, strlen($in))) { echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n"; } while ($out = socket_read($socket, 8192)) { //$out=trim($out,"0xff"); //$out=trim($out,"0x00"); //$this->xieru($out,"sj"); echo $out; } socket_close($socket); }
function sendUSD($text, $pass_server = '000000') { $address = gethostbyname('127.0.0.1'); //IP Адрес вашего компьютера $service_port = 8000; //Порт //$pass_server='000000'; //Пароль $phone = preg_replace('/^\\+/', '', $phone); $socket = socket_create(AF_INET, SOCK_STREAM, 0); if ($socket < 0) { echo "socket create failed reason: " . socket_strerror($socket) . "\n"; } $result = socket_connect($socket, $address, $service_port); if ($result < 0) { echo "socket connect failed.\nReason: ({$result}) " . socket_strerror($result) . "\n"; } $text = iconv("UTF-8", "Windows-1251", $text); $in = base64_encode($pass_server . "#CMD#[USSD]" . $text); //Пример отправки смс //$in = base64_encode($pass_server."#CMD#[USSD]*102#"); //Пример запроса USSD команды $out = ''; socket_write($socket, $in, strlen($in)); //echo "Response:\n\n"; $res = ''; while ($out = socket_read($socket, 2048)) { $res .= $out; } socket_close($socket); $res = iconv("Windows-1251", "UTF-8", $res); if (preg_match('/USSD-RESPONSE\\[.+?\\]:(.+)/is', $res, $m)) { $res = $m[1]; } return $res; }