本文整理汇总了PHP中stream_socket_client函数的典型用法代码示例。如果您正苦于以下问题:PHP stream_socket_client函数的具体用法?PHP stream_socket_client怎么用?PHP stream_socket_client使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了stream_socket_client函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
开发者ID:northoutAnil,项目名称:siezethekey,代码行数:32,代码来源:notification_model.php
示例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;
}
}
开发者ID:h3len,项目名称:Project,代码行数:26,代码来源:PushFeedBack.class.php
示例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>";
}
}
开发者ID:ChesterYue,项目名称:SheSentWeibo,代码行数:31,代码来源:SheSendWeiboServer.php
示例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];
}
开发者ID:difra-org,项目名称:difra,代码行数:32,代码来源:SMTP.php
示例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;
}
开发者ID:AnthonyBSDE,项目名称:phpSockets,代码行数:7,代码来源:phpsockets.class.php
示例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);
}
}
开发者ID:aim-web-projects,项目名称:kobe-chuoh,代码行数:40,代码来源:SocketWrapper.php
示例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]);
}
}
}
开发者ID:keigonec,项目名称:XiiBackend,代码行数:26,代码来源:TraitData.php
示例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;
}
开发者ID:funkjedi,项目名称:PushNotificationPackage,代码行数:37,代码来源:iOSFeedback.php
示例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;
}
}
开发者ID:PhpFoxPro,项目名称:Better-Mobile-Module,代码行数:36,代码来源:apns.class.php
示例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!";
}
}
开发者ID:carriercomm,项目名称:Multicabinet,代码行数:60,代码来源:class.Whois.php
示例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;
}
开发者ID:sebastiendu,项目名称:mmc,代码行数:32,代码来源:xmlrpc.inc.php
示例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);
}
开发者ID:ashutoshdabral7,项目名称:VoyageUp_Server,代码行数:33,代码来源:Push_msg_ios.php
示例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;
}
开发者ID:northdakota,项目名称:platform,代码行数:36,代码来源:WebSocket.php
示例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);
}
开发者ID:sergejey,项目名称:majordomo-app_ircbot,代码行数:25,代码来源:VikingBot.php
示例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;
}
开发者ID:mtisza,项目名称:pfsense,代码行数:32,代码来源:openvpn.widget.php
示例16: sendNotificationIOS
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);
}
开发者ID:armoving,项目名称:nayaritenlinea,代码行数:34,代码来源:complete.php
示例17: testConnectionPool
/**
* 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);
}
开发者ID:sojimaxi,项目名称:FastCGIDaemon,代码行数:34,代码来源:StreamSocketConnectionPoolTest.php
示例18: httpGet
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);
}
开发者ID:CraryPrimitiveMan,项目名称:code-examples,代码行数:30,代码来源:http.php
示例19: InitUrlSocket
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;
}
开发者ID:huangwei2wei,项目名称:kfxt,代码行数:27,代码来源:HJMultiSocket.class.php
示例20: open
/**
* 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;
}
开发者ID:fedeisas,项目名称:lithium,代码行数:33,代码来源:Stream.php
注:本文中的stream_socket_client函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论