本文整理汇总了PHP中socket_connect函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_connect函数的具体用法?PHP socket_connect怎么用?PHP socket_connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了socket_connect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: http_request
function http_request($host, $data)
{
if (!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
echo "socket_create() error!\r\n";
exit;
}
if (!socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1)) {
echo "socket_set_option() error!\r\n";
exit;
}
if (!socket_connect($socket, $host, 80)) {
echo "socket_connect() error!\r\n";
exit;
}
if (!socket_write($socket, $data, strlen($data))) {
echo "socket_write() errror!\r\n";
exit;
}
while ($get = socket_read($socket, 1024, PHP_NORMAL_READ)) {
$content .= $get;
}
socket_close($socket);
$array = array('HTTP/1.1 404 Not Found', 'HTTP/1.1 300 Multiple Choices', 'HTTP/1.1 301 Moved Permanently', 'HTTP/1.1 302 Found', 'HTTP/1.1 304 Not Modified', 'HTTP/1.1 400 Bad Request', 'HTTP/1.1 401 Unauthorized', 'HTTP/1.1 402 Payment Required', 'HTTP/1.1 403 Forbidden', 'HTTP/1.1 405 Method Not Allowed', 'HTTP/1.1 406 Not Acceptable', 'HTTP/1.1 407 Proxy Authentication Required', 'HTTP/1.1 408 Request Timeout', 'HTTP/1.1 409 Conflict', 'HTTP/1.1 410 Gone', 'HTTP/1.1 411 Length Required', 'HTTP/1.1 412 Precondition Failed', 'HTTP/1.1 413 Request Entity Too Large', 'HTTP/1.1 414 Request-URI Too Long', 'HTTP/1.1 415 Unsupported Media Type', 'HTTP/1.1 416 Request Range Not Satisfiable', 'HTTP/1.1 417 Expectation Failed', 'HTTP/1.1 Retry With');
for ($i = 0; $i <= count($array); $i++) {
if (eregi($array[$i], $content)) {
return "{$array[$i]}\r\n";
break;
} else {
return "{$content}\r\n";
break;
}
}
}
示例2: connect
/**
* 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);
}
}
示例3: flushAll
/**
* {@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;
}
示例4: SendMail
function SendMail($email, $subject, $text)
{
$address = 'mail.iptm.ru';
// адрес smtp-сервера
$port = 25;
// порт (стандартный smtp - 25)
// $from = '=?utf-8?b?' . base64_encode('Конференция «Рентгеновская оптика»') . '?= <x-ray@iptm.ru>'; // адрес отправителя
$from = 'x-ray@iptm.ru';
// адрес отправителя
try {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Создаем сокет
if ($socket < 0) {
throw new Exception('socket_create() failed: ' . socket_strerror(socket_last_error()) . "\n");
}
$result = socket_connect($socket, $address, $port);
// Соединяем сокет к серверу
if ($result === false) {
throw new Exception('socket_connect() failed: ' . socket_strerror(socket_last_error()) . "\n");
}
read_smtp_answer($socket);
// Читаем информацию о сервере
write_smtp_response($socket, 'EHLO ' . $_SERVER['SERVER_NAME']);
// Приветствуем сервер
read_smtp_answer($socket);
// ответ сервера
write_smtp_response($socket, 'MAIL FROM:<' . $from . '> BODY=8BITMIME');
// Задаем адрес отправителя
read_smtp_answer($socket);
// ответ сервера
write_smtp_response($socket, 'RCPT TO:<' . $email . '>');
// Задаем адрес получателя
read_smtp_answer($socket);
// ответ сервера
write_smtp_response($socket, 'DATA');
// Готовим сервер к приему данных
read_smtp_answer($socket);
// ответ сервера
$header = "From: " . $from . "\r\n";
$header .= "To: " . $email . "\r\n";
$header .= "Subject: =?utf-8?b?" . base64_encode($subject) . "?=\r\n";
$header .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Mime-Version: 1.0\r\n";
$text = $header . base64_encode($text);
write_smtp_response($socket, $text . "\r\n.");
// Отправляем данные
read_smtp_answer($socket);
// ответ сервера
write_smtp_response($socket, 'QUIT');
// Отсоединяемся от сервера
read_smtp_answer($socket);
// ответ сервера
} catch (Exception $e) {
echo "\nError: " . $e->getMessage();
}
if (isset($socket)) {
socket_close($socket);
}
}
示例5: getsock
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;
}
示例6: pole_display_price
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));
}
}
示例7: connect
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;
}
示例8: connectSocket
/**
* Connects a socket to an external host and port
* @param string $ip_address
* @return boolean
*/
static function connectSocket($sock, $host, $port, &$connect_error = '', $socket_timeout = 5)
{
$attempts = 0;
socket_set_block($sock);
while (!($connected = @socket_connect($sock, $host, $port)) && $attempts++ < $socket_timeout) {
$sock_error = socket_last_error();
if ($sock_error != SOCKET_EINPROGRESS && $sock_error != SOCKET_EALREADY) {
$connect_error = socket_strerror($sock_error);
return false;
}
sleep(125);
}
$connect_buffer = '';
$attempts = 0;
while (!($connect_buffer = @socket_read($sock, 4096, PHP_BINARY_READ)) && $attempts++ < $socket_timeout) {
$sock_error = socket_last_error();
if ($sock_error != SOCKET_EINPROGRESS && $sock_error != SOCKET_EALREADY && $sock_error != SOCKET_EAGAIN) {
$connect_buffer .= socket_strerror($sock_error);
return false;
}
usleep(125);
}
if (!$connected) {
$connect_error = socket_strerror($sock_error);
return false;
}
return $connect_buffer;
}
示例9: connect
public function connect()
{
$this->socketCon = socket_connect($this->socketVar, $this->ip, $this->port);
if (!$this->socketCon) {
die("Cannot Connnect: Exiting With Exception : " . socket_strerror(socket_last_error()) . PHP_EOL);
}
}
示例10: __construct
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;
}
示例11: connect
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();
}
示例12: _tcp_send_request
private static function _tcp_send_request($socket_write_json = null)
{
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (false === $sock) {
echo "sock create error!\n";
}
$address = Config::get("kgi.kgi_mid_server_ip");
$port = Config::get("kgi.kgi_mid_server_port");
try {
$result = socket_connect($sock, $address, $port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($sock)) . "\n";
exit;
die;
}
socket_write($sock, $socket_write_json, strlen($socket_write_json));
while ($out_str = socket_read($sock, 2048)) {
// echo "revice result\n";
// echo $out_str . "\n";
$json_data = json_decode($out_str);
break;
}
socket_close($sock);
} catch (\ErrorException $e) {
//echo $e->getMessage() . "\n";
}
}
示例13: connect
/**
* Gets the OrientSocket, and establishes the connection if required.
*
* @return \PhpOrient\Protocols\Binary\OrientSocket
*
* @throws SocketException
* @throws PhpOrientWrongProtocolVersionException
*/
public function connect()
{
if (!$this->connected) {
if (empty($this->hostname) && empty($this->port)) {
throw new SocketException('Can not initialize a connection ' . 'without connection parameters');
}
if (!extension_loaded("sockets")) {
throw new SocketException('Can not initialize a connection ' . 'without socket extension enabled. Please check you php.ini');
}
$this->_socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_set_block($this->_socket);
socket_set_option($this->_socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => self::READ_TIMEOUT, 'usec' => 0));
socket_set_option($this->_socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => self::WRITE_TIMEOUT, 'usec' => 0));
$x = @socket_connect($this->_socket, $this->hostname, $this->port);
if (!is_resource($this->_socket) || $x === false) {
throw new SocketException($this->getErr() . PHP_EOL);
}
$protocol = Reader::unpackShort($this->read(2));
if ($protocol > $this->protocolVersion) {
throw new PhpOrientWrongProtocolVersionException('Protocol version ' . $protocol . ' is not supported.');
}
//protocol handshake
$this->protocolVersion = $protocol;
$this->connected = true;
}
return $this;
}
示例14: send
/**
* Send message package to the socket server
* Basic layer method
*
* @return mixed
*/
public function send($msg, $is_block = false)
{
if (!$this->host || !$this->port) {
throw new Hush_Socket_Exception("Please set server's host and port first");
}
/* Create a TCP/IP socket. */
$this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->sock < 0) {
echo "socket_create() failed.\nReason: " . socket_strerror($this->sock) . "\n";
}
$result = @socket_connect($this->sock, $this->host, $this->port);
if ($result < 0) {
echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
}
if ($is_block) {
@socket_set_nonblock($this->sock);
}
// add suffix for socket msg
$msg = trim($msg) . "\r\n";
@socket_write($this->sock, $msg, strlen($msg));
$result = @socket_read($this->sock, 2048);
// unserialize data from socket server
$result = unserialize(trim($result));
return $result;
}
示例15: connect
/**
* Connects the TCP socket to the host with the given IP address and port number
*/
public function connect(InetAddress $ipAddress, $portNumber)
{
$this->ipAddress = $ipAddress;
$this->portNumber = $portNumber;
if ($this->socketsEnabled) {
if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
$errorCode = socket_last_error($this->socket);
throw new Exception("Could not create socket: " . socket_strerror($errorCode));
}
if (@(!socket_connect($this->socket, $ipAddress, $portNumber))) {
$errorCode = socket_last_error($this->socket);
throw new Exception("Could not connect socket: " . socket_strerror($errorCode));
}
if ($this->isBlocking) {
socket_set_block($this->socket);
} else {
socket_set_nonblock($this->socket);
}
} else {
if (!($this->socket = fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, 2))) {
throw new Exception("Could not create socket.");
}
stream_set_blocking($this->socket, $this->isBlocking);
}
}