/**
  * Send push notification
  */
 function sendPushOnServer($device_token, $alert, $badge = null)
 {
     // Put private key's passphrase here:
     $passphrase = "123456";
     $liveMode = TRUE;
     $url = $liveMode ? 'ssl://gateway.push.apple.com:2195' : 'ssl://gateway.sandbox.push.apple.com:2195';
     // Put your alert message here:
     //$message = 'Driver accept your request He will come soon!';
     $ctx = stream_context_create();
     stream_context_set_option($ctx, 'ssl', 'local_cert', 'pem/STKPEM.pem');
     stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
     // Open a connection to the APNS server
     $fp = stream_socket_client($url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
     if (!$fp) {
         echo "Failed to connect: {$err} {$errstr}" . PHP_EOL;
         die;
     } else {
         // Create the payload body
         $body['aps'] = array('badge' => $badge, 'alert' => (string) $alert, 'sound' => "default");
         // Encode the payload as JSON
         $payload = json_encode($body);
         // Build the binary notification
         $msg = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($payload)) . $payload;
         // echo $device_token;die;
         // Send it to the server
         $result = fwrite($fp, $msg, strlen($msg));
         fclose($fp);
     }
 }
Example #2
0
 public function ConnectToFeedBack()
 {
     if (!$this->mFeedBacksHost || !$this->mCert) {
         return false;
     }
     $ctx = stream_context_create();
     stream_context_set_option($ctx, 'ssl', 'local_cert', $this->mCert);
     stream_context_set_option($ctx, 'ssl', 'passphrase', $this->mpass);
     $this->mFeedBack = @stream_socket_client($this->mFeedBacksHost, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
     if (!$this->mFeedBack) {
         return 0;
     } else {
         $APNsFeedBack = array();
         while ($devcon = fread($this->mFeedBack, 38)) {
             $arr = unpack("H*", $devcon);
             $rawhex = trim(implode("", $arr));
             $feedbackTime = hexdec(substr($rawhex, 0, 8));
             $feedbackLen = hexdec(substr($rawhex, 8, 4));
             $feedbackDeviceToken = substr($rawhex, 12, 64);
             $arr_tmp['fb_time'] = $feedbackTime;
             $arr_tmp['fb_devi'] = $feedbackDeviceToken;
             $APNsFeedBack[] = $arr_tmp;
         }
         return $APNsFeedBack;
     }
 }
function sendMessage($latestWeibo)
{
    $apnsCert = "ck.pem";
    $pass = "******";
    $serverUrl = "ssl://gateway.sandbox.push.apple.com:2195";
    //之后正式版了,每个用户一个deviceToken要写数据库里
    //并且通过这个id区分发给哪个用户
    $deviceToken = "865cbcd86a020c346550d2a543f9c2db8877f27023260024f0d9f1bb82802c77";
    $badge = 1;
    $sound = "default";
    //中文乱码,要转一下字符集......
    $message = iconv("GBK", "UTF-8", "【") . $latestWeibo->user->screen_name . iconv("GBK", "UTF-8", "】又发微博了: ") . $latestWeibo->text;
    echo "</br> message send: {$message} </br>";
    $body = array("aps" => array("alert" => $message, "badge" => $badge, "sound" => $sound));
    $streamContext = stream_context_create();
    stream_context_set_option($streamContext, "ssl", "local_cert", $apnsCert);
    stream_context_set_option($streamContext, "ssl", "passphrase", $pass);
    $apns = stream_socket_client($serverUrl, $error, $errorString, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $streamContext);
    if (!$apns) {
        echo "failed : {$error}, {$errorString} </br>";
    }
    $payload = json_encode($body);
    $msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack('n', strlen($payload)) . $payload;
    $result = fwrite($apns, $msg);
    fclose($apns);
    if ($result) {
        echo "</br>sending successfully:</br>  {$payload} </br>";
    } else {
        echo "send failed </br>";
    }
}
Example #4
0
 /**
  * Connect
  * @param bool $ping
  * @return resource
  * @throws Temp
  */
 protected function connect($ping = false)
 {
     // use cached connection if exists
     if (!empty(self::$connections[$this->host]) and !feof(self::$connections[$this->host])) {
         // no ping requested, return cached result
         if (!$ping) {
             return self::$connections[$this->host];
         }
         // ping server
         try {
             $this->command('NOOP');
             return self::$connections[$this->host];
         } catch (\Exception $e) {
         }
     }
     // connect
     $context = stream_context_create();
     $errorNum = 0;
     $errorString = '';
     self::$connections[$this->host] = stream_socket_client($this->host, $errorNum, $errorString, self::CONNECT_TIMEOUT, STREAM_CLIENT_CONNECT, $context);
     if (!self::$connections[$this->host]) {
         throw new Temp('Failed to connect SMTP host ' . $this->host);
     }
     $this->read(self::CONNECT_TIMEOUT);
     return self::$connections[$this->host];
 }
 public function connect()
 {
     $this->socket = stream_socket_client('tcp://' . $this->ip . ':' . $this->port, $errno, $errstr, 5);
     $this->Connected = true;
     stream_set_timeout($this->socket, 0);
     return $this;
 }
 /**
  * Class constructor, tries to establish connection
  *
  * @param string $address        Address for stream_socket_client() call,
  *                               e.g. 'tcp://localhost:80'
  * @param int    $timeout        Connection timeout (seconds)
  * @param array  $contextOptions Context options
  *
  * @throws HTTP_Request2_LogicException
  * @throws HTTP_Request2_ConnectionException
  */
 public function __construct($address, $timeout, array $contextOptions = array())
 {
     if (!empty($contextOptions) && !isset($contextOptions['socket']) && !isset($contextOptions['ssl'])) {
         // Backwards compatibility with 2.1.0 and 2.1.1 releases
         $contextOptions = array('ssl' => $contextOptions);
     }
     $context = stream_context_create();
     foreach ($contextOptions as $wrapper => $options) {
         foreach ($options as $name => $value) {
             if (!stream_context_set_option($context, $wrapper, $name, $value)) {
                 throw new HTTP_Request2_LogicException("Error setting '{$wrapper}' wrapper context option '{$name}'");
             }
         }
     }
     set_error_handler(array($this, 'connectionWarningsHandler'));
     $this->socket = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
     restore_error_handler();
     // if we fail to bind to a specified local address (see request #19515),
     // connection still succeeds, albeit with a warning. Throw an Exception
     // with the warning text in this case as that connection is unlikely
     // to be what user wants and as Curl throws an error in similar case.
     if ($this->connectionWarnings) {
         if ($this->socket) {
             fclose($this->socket);
         }
         $error = $errstr ? $errstr : implode("\n", $this->connectionWarnings);
         throw new HTTP_Request2_ConnectionException("Unable to connect to {$address}. Error: {$error}", 0, $errno);
     }
 }
Example #7
0
 private static function getFromRedis()
 {
     if (!XIIS_CACHE_REDIS) {
         return;
     }
     if (!empty(self::$_outputData)) {
         return;
     }
     if (self::$_xiiCacheID == '') {
         return;
     }
     $redis = @stream_socket_client(Yii::$app->redis->hostname . ':' . Yii::$app->redis->port, $errno, $errstr, 1);
     XiiError::ignoreError();
     if (!$redis) {
         self::logRecord([XIIS_DATA_FROM_REDIS => self::FAIL_TO_CONNECT_REDIS]);
     } else {
         $tmp = Yii::$app->redis->get(self::$_xiiCacheID);
         if ($tmp) {
             self::$_outputData = XiiJson::decode($tmp);
             self::$_dataFrom = XIIS_DATA_FROM_REDIS;
             self::logRecord([XIIS_DATA_FROM_REDIS => self::SUCCESS_GET_FROM_REDIS]);
         } else {
             self::logRecord([XIIS_DATA_FROM_REDIS => self::FAIL_GET_FROM_REDIS]);
         }
     }
 }
 /**
  * Gets an array of device UUID unregistration details
  * from the APN feedback service
  *
  * @throws \RuntimeException
  * @return array
  */
 public function getDeviceUUIDs()
 {
     if (!strlen($this->pem)) {
         throw new \RuntimeException("PEM not provided");
     }
     $feedbackURL = "ssl://feedback.push.apple.com:2196";
     if ($this->sandbox) {
         $feedbackURL = "ssl://feedback.sandbox.push.apple.com:2196";
     }
     $data = "";
     $ctx = $this->getStreamContext();
     $fp = stream_socket_client($feedbackURL, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
     if (!$fp) {
         throw new \RuntimeException("Couldn't connect to APNS Feedback service. Error no {$err}: {$errstr}");
     }
     while (!feof($fp)) {
         $data .= fread($fp, 4096);
     }
     fclose($fp);
     if (!strlen($data)) {
         return array();
     }
     $feedbacks = array();
     $items = str_split($data, 38);
     foreach ($items as $item) {
         $feedback = new Feedback();
         $feedbacks[] = $feedback->unpack($item);
     }
     return $feedbacks;
 }
 /**
  * Send Push Notification
  *
  * @param $sToken
  * @param $message
  * @return int
  */
 public function pushNotification($sToken, $message)
 {
     //check if have push certificate key
     $sDesUrl = PHPFOX_DIR . 'file' . PHPFOX_DS . 'accountapi' . PHPFOX_DS . 'certificate' . PHPFOX_DS . 'PushAppCerKey.pem';
     if (file_exists($sDesUrl)) {
         $ctx = stream_context_create();
         stream_context_set_option($ctx, 'ssl', 'local_cert', $sDesUrl);
         stream_context_set_option($ctx, 'ssl', 'passphrase', $this->_sPassPhrase);
         stream_context_set_option($ctx, 'ssl', 'cafile', PHPFOX_DIR . 'file' . PHPFOX_DS . 'accountapi' . PHPFOX_DS . 'cert' . PHPFOX_DS . 'entrust_2048_ca.cer');
         // Open a connection to the APNS server
         $fp = stream_socket_client('ssl://' . $this->_sAPNSUrl, $err, $errstr, 30, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
         if (!$fp) {
             echo 'Failed to connect:' . $err . ' ' . $errstr;
             return;
         }
         echo 'Connected to APNS' . PHP_EOL . $this->_sAPNSUrl;
         // Create the payload body
         $body['aps'] = $message;
         // Encode the payload as JSON
         $payload = json_encode($body);
         // Build the binary notification
         $msg = chr(0) . pack('n', 32) . pack('H*', $sToken) . pack('n', strlen($payload)) . $payload;
         // Send it to the server
         $result = fwrite($fp, $msg, strlen($msg));
         // Close the connection to the server
         fclose($fp);
         return $result;
     }
 }
Example #10
0
 function info()
 {
     if ($this->is_valid()) {
         $tldname = $this->get_tld();
         $domainname = $this->get_domain();
         $whois_server = $this->get_whois_server();
         // If tldname have been found
         if (!empty($whois_server)) {
             // Getting whois information
             $fp = @stream_socket_client($whois_server . ':43', $errno, $errstr, 10);
             if ($errno == 0 && !$fp) {
                 $this->errstr = 'Socket Error: Could not initialize socket';
                 return false;
             } elseif (!$fp) {
                 $this->errstr = 'Socket Error #' . $errno . ': ' . $errstr;
                 return false;
             }
             $dom = $domainname . '.' . $tldname;
             // New IDN
             if ($tldname == "de") {
                 fputs($fp, "-C ISO-8859-1 -T dn {$dom}\r\n");
             } else {
                 fputs($fp, "{$dom}\r\n");
             }
             // Getting string
             $string = '';
             // Checking whois server for .com .net .edu for featch real whois_server
             if ($tldname == 'com' || $tldname == 'net' || $tldname == 'edu') {
                 while (!feof($fp)) {
                     $line = trim(fgets($fp));
                     $string .= $line;
                     $lineArr = split(":", $line);
                     if (strtolower($lineArr[0]) == "whois server") {
                         $whois_server = trim($lineArr[1]);
                     }
                 }
                 // Getting whois information
                 $fp = @fsockopen($whois_server, 43, $errno, $errstr, 10);
                 if (!$fp) {
                     return "Can't connect to {$whois_server}";
                 }
                 fputs($fp, "{$dom}\r\n");
                 $string = '';
                 while (!feof($fp)) {
                     $string .= fgets($fp);
                 }
             } else {
                 while (!feof($fp)) {
                     $string .= fgets($fp);
                 }
             }
             fclose($fp);
             return $string;
         } else {
             return "No whois server for this tld in list!";
         }
     } else {
         return "Domainname isn't valid!";
     }
 }
Example #11
0
/**
 * Return a socket object
 */
function openSocket($proto, $conf)
{
    $errLevel = error_reporting();
    error_reporting(0);
    if ($proto != "ssl://" || $conf[$_SESSION["agent"]]["verifypeer"] != 1 || !function_exists("stream_socket_client")) {
        /*
           Not a SSL connection,
           or simple SSL connection without client certificate and server
           certificate check
           or stream_socket_client function not available (PHP 5 only),
        */
        $sock = fsockopen($proto . $_SESSION["XMLRPC_agent"]["host"], $_SESSION["XMLRPC_agent"]["port"], $errNo, $errString);
        $ret = array($sock, $errNo, $errString);
    } else {
        $context = stream_context_create();
        stream_context_set_option($context, "ssl", "allow_self_signed", False);
        stream_context_set_option($context, "ssl", "verify_peer", True);
        stream_context_set_option($context, "ssl", "cafile", $conf[$_SESSION["agent"]]["cacert"]);
        stream_context_set_option($context, "ssl", "local_cert", $conf[$_SESSION["agent"]]["localcert"]);
        $sock = stream_socket_client('tls://' . $_SESSION["XMLRPC_agent"]["host"] . ":" . $_SESSION["XMLRPC_agent"]["port"], $errNo, $errString, ini_get("default_socket_timeout"), STREAM_CLIENT_CONNECT, $context);
        $ret = array($sock, $errNo, $errString);
    }
    error_reporting($errLevel);
    if ($sock !== False) {
        /* Setting timeout on a SSL socket only works with PHP >= 5.2.1 */
        stream_set_timeout($sock, $conf[$_SESSION["agent"]]["timeout"]);
    }
    return $ret;
}
 function send_message()
 {
     // Put your device token here (without spaces):
     $device_token = $this->get_device_token();
     // Put your private key's passphrase here:
     $passphrase = $this->get_api_key();
     // Put your alert message here:
     $msg_data = $this->get_message();
     $ctx = stream_context_create();
     stream_context_set_option($ctx, 'ssl', 'local_cert', $this->certificate);
     stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
     // Open a connection to the APNS server
     $fp = stream_socket_client($this->get_post_url(), $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
     if (!$fp) {
         exit("Failed to connect: {$err} {$errstr}" . PHP_EOL);
     }
     // Create the payload body
     $body['aps'] = array('alert' => $msg_data['message'], 'badge' => 1, 'sound' => 'default');
     $body['message'] = array('message_ID' => isset($msg_data['message_id']) ? $msg_data['message_id'] : '', 'message_title' => $msg_data['title'], 'message_type' => isset($msg_data['type']) ? $msg_data['type'] : '', 'message_shortDescription' => isset($msg_data['short_descr']) ? $msg_data['short_descr'] : '', 'message_date' => date('d/m/Y'));
     //  "message":{"message_ID":"1012","message_title":"push message","message_type":"push","message_shortDescription":"sample message","message_date": "12/05/2014"}}
     // Encode the payload as JSON
     $payload = json_encode($body);
     // Build the binary notification
     $msg = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($payload)) . $payload;
     // Send it to the server
     $result = fwrite($fp, $msg, strlen($msg));
     /* if (!$result)
                echo 'Message not delivered' . PHP_EOL;
        else
                echo 'Message successfully delivered' . PHP_EOL;*/
     // Close the connection to the server
     fclose($fp);
 }
Example #13
0
 /**
  *
  * @param  string            $host Host to connect to. Default is localhost (127.0.0.1).
  * @param  int               $port Port to connect to. Default is 8080.
  * @return boolean           True on success
  * @throws \RuntimeException
  */
 protected function connect($host, $port)
 {
     $key1 = $this->generateRandomString(32);
     $key2 = $this->generateRandomString(32);
     $key3 = $this->generateRandomString(8, false, true);
     $header = "GET /echo HTTP/1.1\r\n";
     $header .= "Upgrade: WebSocket\r\n";
     $header .= "Connection: Upgrade\r\n";
     $header .= "Host: " . $host . ":" . $port . "\r\n";
     $header .= "Sec-WebSocket-Key1: " . $key1 . "\r\n";
     $header .= "Sec-WebSocket-Key2: " . $key2 . "\r\n";
     $header .= "\r\n";
     $header .= $key3;
     $this->socket = @stream_socket_client('tcp://' . $host . ':' . $port, $errno, $errstr, self::SOCKET_TIMEOUT);
     if (!$this->socket) {
         throw new \RuntimeException(sprintf('WebSocket connection error (%u): %s', $errno, $errstr));
     }
     stream_set_blocking($this->socket, false);
     // do a handshake
     if (!fwrite($this->socket, $header)) {
         throw new \RuntimeException('WebSocket write error');
     }
     /**
      * @todo: check response here. Currently not implemented cause "2 key handshake" is already deprecated.
      * See: http://en.wikipedia.org/wiki/WebSocket#WebSocket_Protocol_Handshake
      */
     // $response = fread($this->socket, 2000);
     return true;
 }
 function __construct($config)
 {
     if (extension_loaded("pcntl")) {
         //Add signal handlers to shut down the bot correctly if its getting killed
         pcntl_signal(SIGTERM, array($this, "signalHandler"));
         pcntl_signal(SIGINT, array($this, "signalHandler"));
     } else {
         //die("Please make sure the pcntl PHP extension is enabled.\n");
     }
     $this->config = $config;
     $this->startTime = time();
     $this->lastServerMessage = $this->startTime;
     ini_set("memory_limit", $this->config['memoryLimit'] . "M");
     if ($config['verifySSL']) {
         $this->socket = stream_socket_client("" . $config['server'] . ":" . $config['port']) or die("Connection error!");
     } else {
         $socketContext = stream_context_create(array("ssl" => array("verify_peer" => false, "verify_peer_name" => false)));
         $this->socket = stream_socket_client("" . $config['server'] . ":" . $config['port'], $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $socketContext) or die("Connection error!");
     }
     stream_set_blocking($this->socket, 0);
     stream_set_timeout($this->socket, 600);
     $this->login();
     $this->loadPlugins();
     $this->main($config);
 }
Example #15
0
function kill_client($port, $remipp)
{
    global $g;
    //$tcpsrv = "tcp://127.0.0.1:{$port}";
    $tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
    $errval;
    $errstr;
    /* open a tcp connection to the management port of each server */
    $fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
    $killed = -1;
    if ($fp) {
        stream_set_timeout($fp, 1);
        fputs($fp, "kill {$remipp}\n");
        while (!feof($fp)) {
            $line = fgets($fp, 1024);
            $info = stream_get_meta_data($fp);
            if ($info['timed_out']) {
                break;
            }
            /* parse header list line */
            if (strpos($line, "INFO:") !== false) {
                continue;
            }
            if (strpos($line, "SUCCESS") !== false) {
                $killed = 0;
            }
            break;
        }
        fclose($fp);
    }
    return $killed;
}
Example #16
0
function sendNotificationIOS()
{
    // Put your device token here (without spaces):
    $deviceToken = '87d4477b81a7f8f7ba80b3f5f043d83dec3c9b0940c708d24f803ef67600966f';
    // Put your private key's passphrase here:
    $passphrase = 'pushchat';
    // Put your alert message here:
    $message = 'My first push notification!';
    ////////////////////////////////////////////////////////////////////////////////
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    // Open a connection to the APNS server
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
    if (!$fp) {
        exit("Failed to connect: {$err} {$errstr}" . PHP_EOL);
    }
    echo 'Connected to APNS' . PHP_EOL;
    // Create the payload body
    $body['aps'] = array('alert' => $message, 'sound' => 'default');
    // Encode the payload as JSON
    $payload = json_encode($body);
    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));
    if (!$result) {
        echo 'Message not delivered' . PHP_EOL;
    } else {
        echo 'Message successfully delivered' . PHP_EOL;
    }
    // Close the connection to the server
    fclose($fp);
}
 /**
  * Test basic connection pool.
  */
 public function testConnectionPool()
 {
     $address = 'tcp://localhost:7000';
     $serverSocket = stream_socket_server($address);
     $connectionPool = new StreamSocketConnectionPool($serverSocket);
     $clientSocket = stream_socket_client($address);
     $clientConnection = new StreamSocketConnection($clientSocket);
     // Should accept connection
     $initialReadableConnections = $connectionPool->getReadableConnections(0);
     $this->assertCount(0, $initialReadableConnections);
     // Ping test
     $clientConnection->write('ping');
     $readableConnections = $connectionPool->getReadableConnections(0);
     $this->assertCount(1, $readableConnections);
     $serverConnection = array_pop($readableConnections);
     $this->assertEquals('ping', $serverConnection->read(4));
     // Close test
     $serverConnection->close();
     $finalReadableConnections = $connectionPool->getReadableConnections(0);
     $this->assertCount(0, $finalReadableConnections);
     $this->assertEquals(0, $connectionPool->count());
     $clientConnection->close();
     // Test that it closes an open connection
     $secondClientSocket = stream_socket_client($address);
     // Accept the connection
     $connectionPool->getReadableConnections(0);
     $connectionPool->close();
     fread($secondClientSocket, 1);
     $this->assertTrue(feof($secondClientSocket));
     fclose($secondClientSocket);
 }
Example #18
0
function httpGet($host, $base_fd)
{
    global $index;
    $fd = stream_socket_client("{$host}", $errno, $errstr, 3, STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT);
    $index[$fd] = 0;
    $event_fd = event_new();
    event_set($event_fd, $fd, EV_WRITE | EV_PERSIST, function ($fd, $events, $arg) use($host) {
        global $times, $limit, $index;
        if (!$index[$fd]) {
            $index[$fd] = 1;
            $out = "GET / HTTP/1.1\r\n";
            $out .= "Host: {$host}\r\n";
            $out .= "Connection: Close\r\n\r\n";
            fwrite($fd, $out);
        } else {
            $str = fread($fd, 4096);
            echo $str, PHP_EOL;
            if (feof($fd)) {
                fclose($fd);
                $times++;
                echo "done\n";
                if ($times == $limit - 1) {
                    event_base_loopexit($arg[1]);
                }
            }
        }
    }, array($event_fd, $base_fd));
    event_base_set($event_fd, $base_fd);
    event_add($event_fd);
}
Example #19
0
 private function InitUrlSocket()
 {
     $i = $CreateCount = $ErrCount = 0;
     $errno = $errstr = 0;
     foreach ($this->Sockets as $Key => $UrlUnit) {
         $Urls = $UrlUnit['Urls'];
         $Port = empty($Urls['port']) ? '80' : $Urls['port'];
         $s = stream_socket_client($Urls['host'] . ':' . $Port, $errno, $errstr, $this->ConnectTimeout, STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT);
         if ($s) {
             stream_set_timeout($s, 0, $this->StreamTimeout);
             $this->Sockets[$Key]['Socket'] = $s;
             $this->Sockets[$Key]['Data'] = '';
             $this->Sockets[$Key]['Succ'] = false;
             $this->Sockets[$Key]['HttpStates'] = array();
             $this->Sockets[$Key]['State'] = 0;
             $this->Sockets[$Key]['Location'] = '';
             $this->Sockets[$Key]['DataLen'] = 0;
             $CreateCount++;
         } elseif ($ErrCount == 3) {
             exit('cannot connection internet');
         } else {
             unset($this->Sockets[$Key]);
             $ErrCount++;
         }
     }
     return $CreateCount;
 }
Example #20
0
 /**
  * Opens a socket and initializes the internal resource handle.
  *
  * @param array $options update the config settings
  * @return mixed Returns `false` if the socket configuration does not contain the
  *         `'scheme'` or `'host'` settings, or if configuration fails, otherwise returns a
  *         resource stream. Throws exception if there is a network error.
  */
 public function open(array $options = array())
 {
     parent::open($options);
     $config = $this->_config;
     if (!$config['scheme'] || !$config['host']) {
         return false;
     }
     $scheme = $config['scheme'] !== 'udp' ? 'tcp' : 'udp';
     $port = $config['port'] ?: 80;
     $host = "{$scheme}://{$config['host']}:{$port}";
     $flags = STREAM_CLIENT_CONNECT;
     if ($config['persistent']) {
         $flags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
     }
     $errorCode = $errorMessage = null;
     $this->_resource = stream_socket_client($host, $errorCode, $errorMessage, $config['timeout'], $flags);
     if ($errorCode || $errorMessage) {
         throw new NetworkException($errorMessage);
     }
     $this->timeout($config['timeout']);
     if (!empty($config['encoding'])) {
         $this->encoding($config['encoding']);
     }
     return $this->_resource;
 }
Example #21
0
 public function refresh($addresses)
 {
     $addresses_with_key = array();
     foreach ($addresses as $address) {
         $key = $address['ip'] . ':' . $address['port'];
         $addresses_with_key[$key] = $address;
     }
     foreach ($addresses_with_key as $key => $address) {
         if (array_key_exists($key, $this->sockets)) {
             continue;
         }
         $socket = stream_socket_client("tcp://{$address['ip']}:{$address['port']}", $error_no, $error_str, 30);
         if ($socket === false) {
             throw new ConnectionException("stream_socket_client failed. reason:" . $error_str, $error_no);
         }
         $this->sockets[$key] = $socket;
     }
     foreach ($this->sockets as $key => $socket) {
         if (array_key_exists($key, $addresses_with_key)) {
             continue;
         }
         fclose($socket);
         unset($this->sockets[$key]);
     }
 }
Example #22
0
 private function getSocket($uriInfo)
 {
     $socket = stream_socket_client("tcp://" . $uriInfo["host"] . $this->getPort($uriInfo), $errno, $errstr, 1, STREAM_CLIENT_ASYNC_CONNECT);
     //STREAM_CLIENT_PERSISTENT
     stream_set_blocking($socket, 1);
     return $socket;
 }
 public function enviariOS($aMensajes)
 {
     $response = ['codigoerror' => 0, 'error' => '', 'data' => []];
     try {
         $streamContext = stream_context_create();
         stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->certificate);
         if ($this->certificatepassword != '') {
             stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->certificatepassword);
         }
         $fp = stream_socket_client($this->url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $streamContext);
         if (!$fp) {
             $response['codigoerror'] = 1;
             $response['error'] = 'Error conectando a APNs: ' . $err;
             return Response::json($response);
         }
         //En este punto ya estamos conectados al APN, mandamos todos los mensajes
         foreach ($aMensajes as $mensaje) {
             $payload['aps'] = ['alert' => $mensaje['mensaje'], 'badge' => 0, 'sound' => 'default'];
             $jsonpayload = json_encode($payload);
             $msg = chr(0) . pack('n', 32) . pack('H*', $mensaje['token']) . pack('n', strlen($jsonpayload)) . $jsonpayload;
             $resultado = fwrite($fp, $msg, strlen($msg));
             $response['data'][] = ['token' => $mensaje['token'], 'resultado' => $resultado];
         }
         return Response::json($response);
     } catch (Exception $e) {
         $response['codigoerror'] = 2;
         $response['error'] = 'Error conectando a APNs: ' . $e->getMessage();
         return Response::json($response);
     }
 }
Example #24
0
 /**
  * Sets up the stream connection
  *
  * @throws \PhpAmqpLib\Exception\AMQPRuntimeException
  * @throws \Exception
  */
 public function connect()
 {
     $errstr = $errno = null;
     $remote = sprintf('%s://%s:%s', $this->protocol, $this->host, $this->port);
     set_error_handler(array($this, 'error_handler'));
     $this->sock = stream_socket_client($remote, $errno, $errstr, $this->connection_timeout, STREAM_CLIENT_CONNECT, $this->context);
     restore_error_handler();
     if (false === $this->sock) {
         throw new AMQPRuntimeException(sprintf('Error Connecting to server(%s): %s ', $errno, $errstr), $errno);
     }
     if (false === stream_socket_get_name($this->sock, true)) {
         throw new AMQPRuntimeException(sprintf('Connection refused: %s ', $remote));
     }
     list($sec, $uSec) = MiscHelper::splitSecondsMicroseconds($this->read_write_timeout);
     if (!stream_set_timeout($this->sock, $sec, $uSec)) {
         throw new AMQPIOException('Timeout could not be set');
     }
     // php cannot capture signals while streams are blocking
     if ($this->canDispatchPcntlSignal) {
         stream_set_blocking($this->sock, 0);
         stream_set_write_buffer($this->sock, 0);
         if (function_exists('stream_set_read_buffer')) {
             stream_set_read_buffer($this->sock, 0);
         }
     } else {
         stream_set_blocking($this->sock, 1);
     }
     if ($this->keepalive) {
         $this->enable_keepalive();
     }
 }
 public function index()
 {
     if (isset($_POST['config']) && isset($_POST['command_test'])) {
         $RESPONSE_END_TAG = "<END/>";
         $addr = gethostbyname("localhost");
         $client = stream_socket_client("tcp://{$addr}:2014", $errno, $errorMessage);
         if ($client === false) {
             throw new UnexpectedValueException("Failed to connect: {$errorMessage}");
         }
         $config = $_POST['config'];
         fwrite($client, 'test ' . $_POST['command_test'] . ' ' . $config);
         $server_response = stream_get_line($client, 1024, $RESPONSE_END_TAG);
         fclose($client);
         $response_code = substr($server_response, 0, 2);
         $server_response = substr($server_response, 3, strlen($server_response));
         $msg = '';
         $time = '';
         if ($response_code == 'OK') {
             $data = explode(') ', $server_response);
             $msg = str_replace('(', '', $data[0]) . '.';
             $time = str_replace(')', '', str_replace('(', '', $data[1])) . '.';
         } else {
             $msg = 'The following error occurred : ' . str_replace(')', '', str_replace('(', '', $server_response)) . '.';
         }
         header('Content-Type: application/json');
         echo json_encode(array('response' => nl2br($msg), 'others' => $time));
         //echo $msg."</br>".$time;
     } else {
         header('Content-Type: application/json');
         echo json_encode(array('response' => 'Missing parameters : Please fill all the required parameters ! ', 'others' => ''));
     }
 }
 private function connect($device_ids, $message)
 {
     if (is_string($device_ids)) {
         $device_ids = (array) $device_ids;
     }
     $streamContext = stream_context_create();
     @stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->config);
     $fp = @stream_socket_client($this->url_service, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $streamContext);
     @stream_set_blocking($fp, 0);
     if (!$fp) {
         return false;
     }
     if ($device_ids[0] != "test") {
         $load = array('aps' => array('alert' => $message, 'badge' => 1, 'sound' => 'chime'));
         $payload = json_encode($load);
         $apnsMessage = null;
         foreach ($device_ids as $token) {
             @($apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload);
         }
         fwrite($fp, $apnsMessage);
         usleep(500000);
         $ivalidToken = $this->pullMessage($fp);
         fclose($fp);
         return $ivalidToken;
     }
     return true;
 }
 public function sendIosPush($registatoin_ids, $message, array $extra)
 {
     set_time_limit(0);
     header('content-type: text/html; charset: utf-8');
     $passphrase = 'password';
     $deviceIds = $registatoin_ids;
     //$message=json_encode($message);
     //$payload = '{"aps":{"alert":"Hello","sound":"default","extra":"'.json_encode($message).'"}}';
     $body['aps'] = array('alert' => $message, 'sound' => "default", 'extra' => json_encode($extra));
     $payload = json_encode($body);
     //$payload=json_encode($message);
     $this->logger->write("INFO :", "inside ios payload" . $payload);
     //$result = 'Start' . '<br />';
     $ctx = stream_context_create();
     stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
     stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
     foreach ($deviceIds as $item) {
         //sleep(1);
         $fp = stream_socket_client($this->iosServer, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
         // Build the binary notification
         $msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
         // Send it to the server
         $result = fwrite($fp, $msg, strlen($msg));
         if ($fp) {
             fclose($fp);
         }
     }
     //set_time_limit(30);
 }
Example #28
0
 public function executeRequest()
 {
     $this->requestExecutionArray =& $this->HTTPRequestArray;
     foreach ($this->requestExecutionArray as $HTTPRequestServer => $HTTPRequestURIArray) {
         foreach ($HTTPRequestURIArray as $HTTPRequestURI => $HTTPRequestURIValues) {
             $this->formatHTTPHeaders();
             $this->activeRequest =& $this->HTTPRequestArray[$HTTPRequestServer][$HTTPRequestURI];
             $fp = @stream_socket_client($this->activeRequest['HTTPTransport'] . $this->activeRequest['HTTPRequestServer'] . ':' . $this->activeRequest['HTTPPort'], $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $this->randomContext());
             if (!$fp) {
                 if ($errno == 0) {
                     $this->HTTPErrorMsg = "http_handler could not connect to {$this->activeRequest}['HTTPRequestServer']:{$this->activeRequest}['HTTPPort']";
                 } else {
                     $this->HTTPErrorMsg = "http_handler could not connect to " . $this->activeRequest['HTTPRequestServer'] . ":" . $this->activeRequest['HTTPPort'] . " (PHP Error Number: {$errno}, Message: {$errstr})";
                 }
                 return false;
             } else {
                 $this->activeRequest['rawHTTPResponse'] = '';
                 fwrite($fp, $this->activeRequest['rawHTTPRequest']);
                 while (!feof($fp)) {
                     $this->activeRequest['rawHTTPResponse'] .= fgets($fp, 2);
                 }
                 fclose($fp);
                 $this->parseResponse();
             }
         }
     }
     unset($this->activeRequest);
     unset($this->requestExecutionArray);
     unset($this->currentRequest);
     unset($this->validTransports);
     return true;
 }
Example #29
0
 public function initialize_apns()
 {
     try {
         $this->ctx = stream_context_create();
         //stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer');
         stream_context_set_option($this->ctx, 'ssl', 'local_cert', $this->getCertificatePath());
         stream_context_set_option($this->ctx, 'ssl', 'passphrase', $this->passphrase);
         // use this if you are using a passphrase
         // Open a connection to the APNS servers
         if ($this->defa == 1) {
             $this->fp = stream_socket_client($this->ssl, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $this->ctx);
         } else {
             $this->fp = stream_socket_client($this->sandboxSsl, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $this->ctx);
         }
         if ($this->fp) {
             Log::info('Successfully connected to server of APNS');
             //echo 'Successfully connected to server of APNS ckUberForXOwner.pem';
         } else {
             Log::error("Error in connection while trying to connect to APNS");
             //echo "Error in connection while trying to connect to APNS ckUberForXOwner.pem";
         }
     } catch (Exception $e) {
         Log::error($e);
     }
 }
Example #30
-1
    /**
     * Connect to server.
     * @param string $server
     * @param int $port
     */
    public function connect($server, $port = 5222)
    {
        $this->logger = \Logger::getLogger(__CLASS__);
        $this->server = $server;
        $this->port = $port;
        $connect = <<<CONNECT
<?xml version="1.0"?>
<stream:stream to="{$server}" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">
CONNECT;
        $type = 'tcp';
        if (5223 == $port) {
            $type = 'ssl';
        }
        $this->socket = \stream_socket_client("{$type}://{$server}:{$port}", $errno, $errstr, $this->timeout);
        if (false === $this->socket) {
            throw new \Exception($errstr, $errno);
            // TODO
        }
        \stream_set_blocking($this->socket, 0);
        // None blocking TODO CHeck error
        $this->stanzaParser = new StanzaParser();
        $this->sendRaw($connect);
        $readBytes = $this->read('stream:features');
        $this->logger->debug($this->stanzaParser->stanzas[0]->name);
        // TODO Error failed connection
    }