本文整理汇总了PHP中stream_socket_client函数的典型用法代码示例。如果您正苦于以下问题:PHP stream_socket_client函数的具体用法?PHP stream_socket_client怎么用?PHP stream_socket_client使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了stream_socket_client函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: sendPushOnServer
/**
* 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);
}
}
示例2: ConnectToFeedBack
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;
}
}
示例3: sendMessage
function sendMessage($latestWeibo)
{
$apnsCert = "ck.pem";
$pass = "123456";
$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>";
}
}
示例4: connect
/**
* 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];
}
示例5: connect
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;
}
示例6: __construct
/**
* 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);
}
}
示例7: getFromRedis
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]);
}
}
}
示例8: getDeviceUUIDs
/**
* 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;
}
示例9: pushNotification
/**
* 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;
}
}
示例10: info
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!";
}
}
示例11: openSocket
/**
* 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;
}
示例12: send_message
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);
}
示例13: connect
/**
*
* @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;
}
示例14: __construct
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);
}
示例15: kill_client
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;
}