public function start() { $host = $this->host; $port = $this->port; echo "app can be acessed from ws://{$host}:{$port}\n"; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { $this->logLastError($socket, "1"); } if (socket_bind($socket, $host, $port) === false) { $this->logLastError($socket, "2"); } if (socket_listen($socket, 5) === false) { $this->logLastError($socket, "3"); } $this->setServerSocket($socket); $serverSocket = $this->getServerSocket(); do { $sockets = $this->getSockets(); //Set up a blocking call to socket_select $write = null; $except = null; $tv_sec = 5; if (socket_select($sockets, $write, $except, $tv_sec) < 1) { continue; } else { $this->setSockets($sockets); } //Handle new Connections if ($this->hasSocket($serverSocket)) { $clientSocket = socket_accept($serverSocket); if ($clientSocket === false) { $this->logLastError($serverSocket, "4"); } else { $this->setClientSocket($clientSocket); $response = "HTTP/1.1 101 Switching Protocols"; $this->respond($clientSocket, $response); } } //Handle Input foreach ($this->getClientSockets() as $clientSocket) { if ($this->hasSocket($clientSocket)) { $message = socket_read($clientSocket, 2048, PHP_NORMAL_READ); if ($message === false) { $this->logLastError($clientSocket, "5"); $this->removeSocket($clientSocket); socket_close($clientSocket); break; } else { $message = trim($message); if (!empty($message)) { $response = $this->trigger("message", ["{$message}"]); $this->respond($clientSocket, $response); } } } } } while (true); socket_close($serverSocket); }
/** * Connects the TCP socket to the host with the given IP address and port * number * * Depending on whether PHP's sockets extension is loaded, this uses either * <var>socket_create</var>/<var>socket_connect</var> or * <var>fsockopen</var>. * * @param string $ipAddress The IP address to connect to * @param int $portNumber The TCP port to connect to * @param int $timeout The timeout in milliseconds * @throws SocketException if an error occurs during connecting the socket */ public function connect($ipAddress, $portNumber, $timeout) { $this->ipAddress = $ipAddress; $this->portNumber = $portNumber; if ($this->socketsEnabled) { if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { throw new SocketException(socket_last_error($this->socket)); } socket_set_nonblock($this->socket); @socket_connect($this->socket, $ipAddress, $portNumber); $write = array($this->socket); $read = $except = array(); $sec = floor($timeout / 1000); $usec = $timeout % 1000; if (!socket_select($read, $write, $except, $sec, $usec)) { $errorCode = socket_last_error($this->socket); } else { $errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR); } if ($errorCode) { throw new SocketException($errorCode); } socket_set_block($this->socket); } else { if (!($this->socket = @fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000))) { throw new SocketException($socketErrstr); } stream_set_blocking($this->socket, true); } }
/** * {@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; }
protected function connectSocket() { if (filter_var($this->host, FILTER_VALIDATE_IP)) { $ip = $this->host; } else { $ip = gethostbyname($this->host); if ($ip == $this->host) { throw new MongoConnectionException(sprintf('couldn\'t get host info for %s', $this->host)); } } // For some reason, PHP doesn't currently allow resources opened with // fsockopen/pfsockopen to be used with socket_* functions, but HHVM does. if (defined('HHVM_VERSION')) { $this->socket = pfsockopen($ip, $this->port, $errno, $errstr, $this->connectTimeoutMS / 1000); if ($this->socket === false) { $this->socket = null; throw new MongoConnectionException(sprintf("unable to connect to {$ip}:{$this->port} because: %s", "{$errstr} ({$errno})")); } } else { $this->socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp")); if (!$this->socket) { throw new MongoConnectionException(sprintf('error creating socket: %s', socket_strerror(socket_last_error()))); } $connected = socket_connect($this->socket, $ip, $this->port); if (!$connected) { throw new MongoConnectionException(sprintf("unable to connect to {$ip}:{$this->port} because: %s", socket_strerror(socket_last_error()))); } } }
function lw_start() { if ($this->Server['Started'] !== false) { return false; } if (($this->Handler = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { $this->lw_log('socket_create() failed: reason: ' . socket_strerror(socket_last_error($this->Handler))); return false; } else { $this->lw_log('Socket created'); } socket_set_nonblock($this->Handler); if (($ret = socket_bind($this->Handler, $this->Options['Address'], $this->Options['Port'])) !== true) { $this->lw_log('socket_bind() failed: reason: ' . socket_strerror(socket_last_error($this->Handler))); return false; } else { $this->lw_log('Socket bindet'); } if (socket_listen($this->Handler, isset($this->Options['ConnectLimit']) ? $this->Options['ConnectLimit'] : 5) !== true) { $this->lw_log('socket_listen() failed: reason: ' . socket_strerror(socket_last_error($this->Handler))); return false; } //socket_set_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE,2); //echo 'SO_KEEPALIVE : '.socket_get_option($this->Handler,SOL_SOCKET,SO_KEEPALIVE).RN; //echo 'SO_REUSEADDR : '.socket_get_option($this->Handler,SOL_SOCKET,SO_REUSEADDR).RN; //echo 'SO_RCVBUF : '.socket_get_option($this->Handler,SOL_SOCKET,SO_RCVBUF).RN; //echo 'SO_SNDBUF : '.socket_get_option($this->Handler,SOL_SOCKET,SO_SNDBUF).RN; //echo 'SO_DONTROUTE : '.socket_get_option($this->Handler,SOL_SOCKET,SO_DONTROUTE).RN; //echo 'SOCKET_EHOSTUNREACH : '.SOCKET_EHOSTUNREACH.RN; //echo 'SO_BROADCAST : '.socket_get_option($this->Handler,SOL_SOCKET,SO_BROADCAST).RN; $this->Server['Started'] = microtime(true); /// php 5 // wb_create_timer ($_CONTROL['window'], $_SERVER['timer'][0], CL_SOCKET_TIMER); return true; }
function run($port = 10000, $opts = array()) { global $argv; $addr = "127.0.0.1"; $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $__condtmpvar4 = Null; if (isset($opts["file"])) { $__condtmpvar4 = $opts["file"]; } else { $__condtmpvar4 = NULL; } $file = $__condtmpvar4; $repl_vars = get_repl_vars($file); if ($file) { compile_file($file); } else { NULL; } \NamespaceNode::$repling = TRUE; socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($sock, $addr, $port); socket_listen($sock, 5); prn("Initializing Reph server on ", $addr, ":", $port); accept_loop($sock, $repl_vars); return socket_close($sock); }
/** * Constructor. * * @param array $options an array of options. Having the following keys * 'domain' => the protocol family to be used by the socket * 'type' => the type of communication to be used by the socket * 'protocol' => protocol within the specified domain to be used when communicating * 'address' => addres (if domain is inet) or path (if domain is unix) * 'port' => port to listen on (if inet) * 'backlog' => maximum of backlog incoming connections taht will be queued for processing * */ public function __construct(array $options) { if (!($this->socket = socket_create($options['domain'], $options['type'], $options['protocol']))) { throw new SocketException(); } $this->options = $options; }
/** * 连接到服务器 * 接受一个浮点型数字作为超时,整数部分作为sec,小数部分*100万作为usec * * @param string $host 服务器地址 * @param int $port 服务器地址 * @param float $timeout 超时默认值,连接,发送,接收都使用此设置 * @param bool $udp_connect 是否启用connect方式 */ function connect($host, $port, $timeout = 0.1, $udp_connect = true) { //判断超时为0或负数 if (empty($host) or empty($port) or $timeout <= 0) { $this->errCode = -10001; $this->errMsg = "param error"; return false; } $this->host = $host; $this->port = $port; $this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); $this->set_timeout($timeout, $timeout); //$this->set_bufsize($this->sendbuf_size, $this->recvbuf_size); //是否用UDP Connect if ($udp_connect !== true) { return true; } if (socket_connect($this->sock, $host, $port)) { //清理connect前的buffer数据遗留 while (@socket_recv($this->sock, $buf, 65535, MSG_DONTWAIT)) { } return true; } else { $this->set_error(); return false; } }
function WakeOnLan($addr, $mac_address, $socket_number) { $addr_byte = explode(':', $mac_address); $hw_addr = ''; for ($a = 0; $a < 6; $a++) { $hw_addr .= chr(hexdec($addr_byte[$a])); $msg = chr(255) . chr(255) . chr(255) . chr(255) . chr(255) . chr(255); for ($a = 1; $a <= 16; $a++) { $msg .= $hw_addr; // send it to the broadcast address using UDP // SQL_BROADCAST option isn't help!! $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($s == false) { echo "Error creating socket!\n"; echo "Error code is '" . socket_last_error($s) . "' - " . socket_strerror(socket_last_error($s)); return FALSE; } else { // setting a broadcast option to socket: $opt_ret = socket_set_option($s, 1, 6, TRUE); if ($opt_ret < 0) { echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n"; return FALSE; } if (socket_sendto($s, $msg, strlen($msg), 0, $ip_address, $socket_number)) { echo "Magic Packet sent successfully!"; socket_close($s); return TRUE; } else { echo "Magic packet failed!"; return FALSE; } } } } }
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); } } }
function coop_send($message) { if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Couldn't create socket: [{$errorcode}] {$errormsg} \n"); } //Connect socket to remote server if (!socket_connect($sock, COOPSERVER, COOPPORT)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not connect: [{$errorcode}] {$errormsg} \n"); } //Send the message to the server if (!socket_send($sock, $message, strlen($message), 0)) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); die("Could not send data: [{$errorcode}] {$errormsg} \n"); } $buf = 'my buffer'; if (false !== ($bytes = socket_recv($sock, $buf, 1024, 0))) { echo "Read {$bytes} bytes of socket_recv(). close socket ..."; } else { echo "socket_recv() error; Reason: " . socket_strerror(socket_last_error($socket)) . "\n"; } socket_close($sock); return $buf; }
/** * Create a Socket Server on the given domain and port * @param $domain String * @param $port Float[optional] */ function create($domain, $port = 9801) { $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($this->socket, $domain, $port); socket_listen($this->socket); socket_set_block($this->socket); }
private function get_peers_blocking($info_hash, $host = "router.bittorrent.com", $port = 6881) { //create a UDP socket to send commands through $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //Create Command Packet $packet = bencode::encode(array("id" => $this->get_unique_node_id(), "info_hash" => hex2bin($info_hash)), array("q" => "get_peers", "t" => $this->unique_id(), "y" => "q")); socket_sendto($socket, $packet, strlen($packet), 0, $host, $port); //set timeout $timeout = array('sec' => 5, 'usec' => 0); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout); $time = time(); //recieve data try { socket_recvfrom($socket, $buf, 12000, 0, $host, $port); } catch (Exception $e) { echo "Error"; return FALSE; } //have to manually do the timeout, cant seem to get info from this socket if (time() - $time >= 4) { socket_close($socket); return FALSE; } //close socket so bad shit don't happen socket_close($socket); return nodeExtract::return_nodes(bencode::decode($buf)); }
public function search($st = 'ssdp:all', $mx = 2, $man = 'ssdp:discover', $from = null, $port = null, $sockTimout = '2') { $request = 'M-SEARCH * HTTP/1.1' . "\r\n"; $request .= 'HOST: 239.255.255.250:1900' . "\r\n"; $request .= 'MAN: "' . $man . '"' . "\r\n"; $request .= 'MX: ' . $mx . '' . "\r\n"; $request .= 'ST: ' . $st . '' . "\r\n"; $request .= 'USER-AGENT: ' . $this->user_agent . "\r\n"; $request .= "\r\n"; $socket = socket_create(AF_INET, SOCK_DGRAM, 0); socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, true); socket_sendto($socket, $request, strlen($request), 0, '239.255.255.250', 1900); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $sockTimout, 'usec' => '0')); $response = array(); do { $buf = null; socket_recvfrom($socket, $buf, 1024, MSG_WAITALL, $from, $port); if (!is_null($buf)) { $data = $this->parseSearchResponse($buf); $response[$data['usn']] = $data; } } while (!is_null($buf)); socket_close($socket); return $response; }
function getsock($addr, $port) { $socket = null; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false || $socket === null) { $error = socket_strerror(socket_last_error()); $msg = "socket create(TCP) failed"; echo "ERR: {$msg} '{$error}'\n"; return null; } $res = socket_connect($socket, $addr, $port); if ($res === false) { $error = socket_strerror(socket_last_error()); $msg = '<center class="alert alert-danger bs-alert-old-docs">CGMiner is not running...If it is not restart after minutes ,please try to reboot.</center>'; socket_close($socket); echo $msg; @exec('sudo service cgminer stop '); @exec('sudo service cgminer stop '); @exec('sudo service cgminer stop '); $network = get_network(); $gateway = $network['gateway_id']; @exec('sudo route add default gw ' . $gateway); //sleep(3); //@exec('sudo service cgminer start &'); //showmsg($msg,'?c=home&m=reboot','10000'); //echo "ERR: $msg '$error'\n"; //exit; return null; } return $socket; }
private function getSock() { if ($this->sock == NULL) { $this->sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); } return $this->sock; }
protected function connect($host, $port) { $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); set_error_handler(__CLASS__ . '::handleError'); $this->isAvailable = socket_connect($this->socket, $host, $port); restore_error_handler(); }
public function __construct(Server $server, $password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50) { $this->server = $server; $this->workers = []; $this->password = (string) $password; $this->server->getLogger()->info("Starting remote control listener"); if ($this->password === "") { $this->server->getLogger()->critical("RCON can't be started: Empty password"); return; } $this->threads = (int) max(1, $threads); $this->clientsPerThread = (int) max(1, $clientsPerThread); $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) { $this->server->getLogger()->critical("RCON can't be started: " . socket_strerror(socket_last_error())); $this->threads = 0; return; } socket_set_block($this->socket); for ($n = 0; $n < $this->threads; ++$n) { $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); } socket_getsockname($this->socket, $addr, $port); $this->server->getLogger()->info("RCON running on {$addr}:{$port}"); }
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 getsock($port) { $socket = null; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false || $socket === null) { $error = socket_strerror(socket_last_error()); $msg = "socket create({$port}) failed"; echo "ERR: {$msg} '{$error}'\n"; return NULL; } socket_set_nonblock($socket); $res = socket_connect($socket, API_HOST, $port); $timeout = 50; while ($res === false && $timeout > 0) { $err = socket_last_error($socket); echo "."; if ($timeout > 1 && ($err == 115 || $err == 114)) { $timeout--; usleep(50); $res = socket_connect($socket, API_HOST, $port); continue; } $error = socket_strerror($err); $msg = "socket connect({$port}) failed"; echo "ERR: {$msg} '{$error}'\n"; socket_close($socket); return NULL; } socket_set_block($socket); return $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 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); }
public function connect($address = "", $port = "") { global $merchantAddress; if ($this->connected) { $this->close(); } $a = Tools::address($merchantAddress); if (empty($port) || !is_integer($port)) { $port = intval($a['port']); } if (empty($address)) { $address = $a['address']; } $address = gethostbyname($address); $this->address = $address; $this->port = $port; $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket === false) { return false; } $result = socket_connect($this->socket, $this->address, $this->port); if ($result === false) { return false; } $this->connectmessage = @socket_read($this->socket, 1024 * 1024, PHP_NORMAL_READ); $this->connected = true; return true; }
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; }
/** * Open a socket if there isn't one open already, return it. * Returns false on error. * * @return bool|resource */ protected function getSocket() { if ($this->socket !== null) { return $this->socket; } $ip = $this->getIP(); if (!$ip) { $this->log("DNS error"); $this->markDown(); return false; } $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_nonblock($this->socket); wfSuppressWarnings(); $ok = socket_connect($this->socket, $ip, $this->port); wfRestoreWarnings(); if (!$ok) { $error = socket_last_error($this->socket); if ($error !== self::EINPROGRESS) { $this->log("connection error: " . socket_strerror($error)); $this->markDown(); return false; } } return $this->socket; }
public function __construct($MyProperties, $NodeList) { $this->MyProperties = $MyProperties; $this->NodeList = $NodeList; $this->Sender = new Sender($this->MyProperties); $this->Reciever = new Reciever($this->NodeList); $this->state = "Initialized"; $this->currentTerm = 0; $this->votedFor = null; $this->votes = 0; $this->log = array(); $this->commitIndex = 0; $this->lastApplied = 0; $this->lastLogIndex = 0; $this->nextIndex = array(); $this->matchIndex = array(); $this->timeoutinterval = 0.15; $this->heartbeatinterval = 0.075; $this->LeaderId = null; $this->close = false; $this->connectIndex = 0; set_time_limit(0); $this->socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); socket_bind($this->socket, $MyProperties->ServerAddr, $MyProperties->PortNo + count($NodeList->Nodes) + 1); socket_listen($this->socket); $this->clientSocket = false; socket_set_nonblock($this->socket); $this->exiting = false; $this->exitcount = 0; }
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 __construct($host, $port) { $ipAddr = self::DEFAULT_IPADDR; if (false === ip2long($host)) { $ipAddr = gethostbyname($host); } else { $ipAddr = $host; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (false === $socket) { throw new PhpBuf_RPC_Socket_Exception('socket creation fail:' . socket_strerror(socket_last_error())); } $connected = socket_connect($socket, $ipAddr, $port); if (false === $connected) { throw new PhpBuf_RPC_Socket_Exception('socket connection fail:' . socket_strerror(socket_last_error())); } socket_set_nonblock($socket); // socket_set_timeout($socket, 5); socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 1)); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); if (defined('TCP_NODELAY')) { socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1); } $this->socket = $socket; }
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; }