本文整理汇总了PHP中socket_import_stream函数的典型用法代码示例。如果您正苦于以下问题:PHP socket_import_stream函数的具体用法?PHP socket_import_stream怎么用?PHP socket_import_stream使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了socket_import_stream函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: tcpStreamInitializer
/**
* Initializes a TCP stream resource.
*
* @param ParametersInterface $parameters Initialization parameters for the connection.
*
* @return resource
*/
protected function tcpStreamInitializer(ParametersInterface $parameters)
{
$uri = "tcp://{$parameters->host}:{$parameters->port}";
$flags = STREAM_CLIENT_CONNECT;
if (isset($parameters->async_connect) && (bool) $parameters->async_connect) {
$flags |= STREAM_CLIENT_ASYNC_CONNECT;
}
if (isset($parameters->persistent) && (bool) $parameters->persistent) {
$flags |= STREAM_CLIENT_PERSISTENT;
$uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/{$path}";
}
$resource = @stream_socket_client($uri, $errno, $errstr, (double) $parameters->timeout, $flags);
if (!$resource) {
$this->onConnectionError(trim($errstr), $errno);
}
if (isset($parameters->read_write_timeout)) {
$rwtimeout = (double) $parameters->read_write_timeout;
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
$timeoutSeconds = floor($rwtimeout);
$timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
}
if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
$socket = socket_import_stream($resource);
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
}
return $resource;
}
示例2: listen
public function listen($port, $host = '127.0.0.1', $protocol = 'tcp')
{
if (strpos($host, ':') !== false) {
// enclose IPv6 addresses in square brackets before appending port
$host = '[' . $host . ']';
}
$opts = ['socket' => ['backlog' => 1024, 'so_reuseport' => 1]];
$flags = $protocol == 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
$context = stream_context_create($opts);
$this->master = @stream_socket_server("{$protocol}://{$host}:{$port}", $errorCode, $errorMessage, $flags, $context);
if (false === $this->master) {
$message = "Could not bind to tcp://{$host}:{$port}: {$errorMessage}";
throw new ConnectionException($message, $errorCode);
}
// Try to open keep alive for tcp and disable Nagle algorithm.
if (function_exists('socket_import_stream') && $protocol == 'tcp') {
$socket = socket_import_stream($this->master);
@socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
@socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
}
stream_set_blocking($this->master, 0);
$this->loop->addReadStream($this->master, function ($master) {
$newSocket = stream_socket_accept($master, 0, $remote_address);
if (false === $newSocket) {
$this->notifyError(new \RuntimeException('Error accepting new connection'));
return;
}
$this->handleConnection($newSocket);
});
return $this;
}
示例3: createReceiver
public function createReceiver($address)
{
if (!defined('MCAST_JOIN_GROUP')) {
throw new BadMethodCallException('MCAST_JOIN_GROUP not defined (requires PHP 5.4+)');
}
if (!function_exists('socket_import_stream')) {
throw new BadMethodCallException('Function socket_import_stream missing (requires ext-sockets and PHP 5.4+)');
}
$parts = parse_url('udp://' . $address);
$stream = @stream_socket_server('udp://0.0.0.0:' . $parts['port'], $errno, $errstr, STREAM_SERVER_BIND);
if ($stream === false) {
throw new RuntimeException('Unable to create receiving socket: ' . $errstr, $errno);
}
$socket = socket_import_stream($stream);
if ($stream === false) {
throw new RuntimeException('Unable to access underlying socket resource');
}
// allow multiple processes to bind to the same address
$ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
if ($ret === false) {
throw new RuntimeException('Unable to enable SO_REUSEADDR');
}
// join multicast group and bind to port
$ret = socket_set_option($socket, IPPROTO_IP, MCAST_JOIN_GROUP, array('group' => $parts['host'], 'interface' => 0));
if ($ret === false) {
throw new RuntimeException('Unable to join multicast group');
}
return new DatagramSocket($this->loop, $stream);
}
示例4: setTcpNoDelay
/**
* Toggle TCP nodelay flag (nagle algorithm) for the given socket.
*
* @param resource $socket The socket resource.
* @param bool $nodelay New setting fpr tcp_nodelay.
* @return bool Returns true when the setting was applied.
*/
public static function setTcpNoDelay($socket, bool $nodelay) : bool
{
static $nodelay;
static $sockets;
if ($nodelay ?? ($nodelay = \version_compare(\PHP_VERSION, '7.1.0', '>='))) {
return \stream_context_set_option($socket, 'socket', 'tcp_nodelay', $nodelay);
}
if ($sockets ?? ($sockets = \extension_loaded('sockets'))) {
if ($resource = @\socket_import_stream($socket)) {
return @\socket_set_option($resource, \SOL_TCP, \TCP_NODELAY, $nodelay ? 1 : 0);
}
}
return false;
}
示例5: createSocketServer
private function createSocketServer($uri)
{
$scheme = parse_url($uri, PHP_URL_SCHEME);
if ($scheme == 'unix') {
$uri = 'unix://' . parse_url($uri, PHP_URL_PATH);
}
$errno = 0;
$errstr = '';
$context = @stream_context_create($this->settings);
$server = @stream_socket_server($uri, $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);
if (function_exists('socket_import_stream')) {
if ($scheme === 'tcp' || $scheme === 'unix') {
$socket = socket_import_stream($server);
socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, (int) $this->keepAlive);
if ($scheme === 'tcp') {
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $this->noDelay);
}
}
}
if ($server === false) {
throw new Exception($errstr, $errno);
}
return $server;
}
示例6: tcpStreamInitializer
/**
* Initializes a TCP stream resource.
*
* @param ConnectionParametersInterface $parameters Parameters used to initialize the connection.
* @return resource
*/
private function tcpStreamInitializer(ConnectionParametersInterface $parameters)
{
$uri = "tcp://{$parameters->host}:{$parameters->port}/";
$flags = STREAM_CLIENT_CONNECT;
if (isset($parameters->async_connect) && $parameters->async_connect) {
$flags |= STREAM_CLIENT_ASYNC_CONNECT;
}
if (isset($parameters->persistent) && $parameters->persistent) {
$flags |= STREAM_CLIENT_PERSISTENT;
}
$resource = @stream_socket_client($uri, $errno, $errstr, $parameters->timeout, $flags);
if (!$resource) {
$this->onConnectionError(trim($errstr), $errno);
}
if (isset($parameters->read_write_timeout)) {
$rwtimeout = $parameters->read_write_timeout;
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
$timeoutSeconds = floor($rwtimeout);
$timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
}
if (isset($parameters->tcp_nodelay) && version_compare(PHP_VERSION, '5.4.0') >= 0) {
$socket = socket_import_stream($resource);
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
}
return $resource;
}
示例7: createStreamSocket
/**
* {@inheritdoc}
*/
protected function createStreamSocket(ParametersInterface $parameters, $address, $flags, $context = null)
{
$socket = null;
$timeout = isset($parameters->timeout) ? (double) $parameters->timeout : 5.0;
$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags);
if (!$resource) {
$this->onConnectionError(trim($errstr), $errno);
}
if (isset($parameters->read_write_timeout) && function_exists('socket_import_stream')) {
$rwtimeout = (double) $parameters->read_write_timeout;
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
$timeout = array('sec' => $timeoutSeconds = floor($rwtimeout), 'usec' => ($rwtimeout - $timeoutSeconds) * 1000000);
$socket = $socket ?: socket_import_stream($resource);
@socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout);
@socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
}
if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
$socket = $socket ?: socket_import_stream($resource);
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
}
return $resource;
}
示例8: getStream
/**
* Creates stream according to options passed in constructor.
*
* @return resource
*/
protected function getStream()
{
if ($this->stream === null) {
// TODO: SSL
// see https://github.com/nrk/predis/blob/v1.0/src/Connection/StreamConnection.php
$uri = "tcp://{$this->options["host"]}:{$this->options["port"]}";
$flags = STREAM_CLIENT_CONNECT;
if (isset($this->options["async_connect"]) && !!$this->options["async_connect"]) {
$flags |= STREAM_CLIENT_ASYNC_CONNECT;
}
if (isset($this->options["persistent"]) && !!$this->options["persistent"]) {
$flags |= STREAM_CLIENT_PERSISTENT;
if (!isset($this->options["path"])) {
throw new ClientException("If you need persistent connection, you have to specify 'path' option.");
}
$uri .= strpos($this->options["path"], "/") === 0 ? $this->options["path"] : "/" . $this->options["path"];
}
$this->stream = @stream_socket_client($uri, $errno, $errstr, (double) $this->options["timeout"], $flags);
if (!$this->stream) {
throw new ClientException("Could not connect to {$this->options["host"]}:{$this->options["port"]}: {$errstr}.", $errno);
}
if (isset($this->options["read_write_timeout"])) {
$readWriteTimeout = (double) $this->options["read_write_timeout"];
if ($readWriteTimeout < 0) {
$readWriteTimeout = -1;
}
$readWriteTimeoutSeconds = floor($readWriteTimeout);
$readWriteTimeoutMicroseconds = ($readWriteTimeout - $readWriteTimeoutSeconds) * 10000000.0;
stream_set_timeout($this->stream, $readWriteTimeoutSeconds, $readWriteTimeoutMicroseconds);
}
if (isset($this->options["tcp_nodelay"]) && function_exists("socket_import_stream")) {
$socket = socket_import_stream($this->stream);
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $this->options["tcp_nodelay"]);
}
if ($this->options["async"]) {
stream_set_blocking($this->stream, 0);
}
}
return $this->stream;
}
示例9: stream_socket_server
<?php
$stream0 = stream_socket_server("udp://0.0.0.0:58380", $errno, $errstr, STREAM_SERVER_BIND);
$sock0 = socket_import_stream($stream0);
leak_variable($stream0, true);
$stream1 = stream_socket_server("udp://0.0.0.0:58381", $errno, $errstr, STREAM_SERVER_BIND);
$sock1 = socket_import_stream($stream1);
leak_variable($sock1, true);
echo "Done.\n";
示例10: M_Connect
function M_Connect(&$conn)
{
$ctx = stream_context_create();
if ($conn['method'] == M_CONN_SSL) {
stream_context_set_option($ctx, 'ssl', 'cafile', $conn['ssl_cafile']);
stream_context_set_option($ctx, 'ssl', 'verify_peer', $conn['ssl_verify']);
stream_context_set_option($ctx, 'ssl', 'verify_peer_name', $conn['ssl_verify']);
stream_context_set_option($ctx, 'ssl', 'allow_self_signed', !$conn['ssl_verify']);
stream_context_set_option($ctx, 'ssl', 'disable_compression', true);
stream_context_set_option($ctx, 'ssl', 'ciphers', $conn['ssl_ciphers']);
stream_context_set_option($ctx, 'ssl', 'SNI_enabled', true);
if ($conn['ssl_cert'] != NULL) {
stream_context_set_option($ctx, 'ssl', 'local_cert', $conn['ssl_cert']);
}
if ($conn['ssl_key'] != NULL) {
stream_context_set_option($ctx, 'ssl', 'local_pk', $conn['ssl_key']);
}
}
/* Always use TCP, not ssl:// as we need to upgrade it later after we set socket
* options for best compatibility */
$url = "tcp://" . $conn['host'] . ":" . $conn['port'];
$error = "";
$errorString = "";
$conn['fd'] = @stream_socket_client($url, $error, $errorString, $conn['conn_timeout'], STREAM_CLIENT_CONNECT, $ctx);
if (!$conn['fd']) {
$conn['conn_error'] = "Failed to connect to {$url}: {$error}: {$errorString}";
return false;
}
/* Use blocking reads, we'll set timeouts later */
stream_set_blocking($conn['fd'], TRUE);
/* Disable the nagle algorithm, should reduce latency */
if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
$socket = socket_import_stream($conn['fd']);
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) 1);
}
/* Upgrade the connection to use SSL/TLS. We need to do this *after* setting Nagle due to
* bug https://bugs.php.net/bug.php?id=70939 */
if (!stream_socket_enable_crypto($conn['fd'], true, $conn['ssl_protocols'])) {
$conn['conn_error'] = "Failed to negotiate SSL/TLS";
fclose($conn['fd']);
$conn['fd'] = false;
return false;
}
if ($conn['verify_conn'] && !M_verifyping($conn)) {
$conn['conn_error'] = "PING request failed";
fclose($conn['fd']);
$conn['fd'] = false;
return false;
}
return true;
}
示例11: getLastSocketError
/**
* Get the last error from the client socket
*
* @return string The error string
*/
private function getLastSocketError()
{
$errStr = '-1: Unknown error';
if (function_exists('socket_import_stream')) {
$socket = socket_import_stream($this->socket);
$errCode = socket_last_error($socket);
$errStr = $errCode . ': ' . socket_strerror($errCode);
}
return $errStr;
}
示例12: checkConnection
/**
* Check connection is successfully established or faild.
*
* @param resource $socket
* @return void
*/
public function checkConnection($socket)
{
// Check socket state.
if ($address = stream_socket_get_name($socket, true)) {
// Remove write listener.
Worker::$globalEvent->del($socket, EventInterface::EV_WRITE);
// Nonblocking.
stream_set_blocking($socket, 0);
stream_set_read_buffer($socket, 0);
// Try to open keepalive for tcp and disable Nagle algorithm.
if (function_exists('socket_import_stream') && $this->transport === 'tcp') {
$raw_socket = socket_import_stream($socket);
socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
}
// Register a listener waiting read event.
Worker::$globalEvent->add($socket, EventInterface::EV_READ, array($this, 'baseRead'));
// There are some data waiting to send.
if ($this->_sendBuffer) {
Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
}
$this->_status = self::STATUS_ESTABLISH;
$this->_remoteAddress = $address;
// Try to emit onConnect callback.
if ($this->onConnect) {
try {
call_user_func($this->onConnect, $this);
} catch (\Exception $e) {
Worker::log($e);
exit(250);
} catch (\Error $e) {
Worker::log($e);
exit(250);
}
}
// Try to emit protocol::onConnect
if (method_exists($this->protocol, 'onConnect')) {
try {
call_user_func(array($this->protocol, 'onConnect'), $this);
} catch (\Exception $e) {
Worker::log($e);
exit(250);
} catch (\Error $e) {
Worker::log($e);
exit(250);
}
}
} else {
// Connection failed.
$this->emitError(WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(microtime(true) - $this->_connectStartTime, 4) . ' seconds');
if ($this->_status === self::STATUS_CLOSING) {
$this->destroy();
}
if ($this->_status === self::STATUS_CLOSED) {
$this->onConnect = null;
}
}
}
示例13: var_dump
<?php
var_dump(socket_import_stream());
var_dump(socket_import_stream(1, 2));
var_dump(socket_import_stream(1));
var_dump(socket_import_stream(new stdclass()));
var_dump(socket_import_stream(fopen(__FILE__, "rb")));
var_dump(socket_import_stream(socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)));
$s = stream_socket_server("udp://127.0.0.1:58392", $errno, $errstr, STREAM_SERVER_BIND);
var_dump($s);
var_dump(fclose($s));
var_dump(socket_import_stream($s));
echo "Done.";
示例14: stream_socket_server
<?php
$stream = stream_socket_server("udp://0.0.0.0:58381", $errno, $errstr, STREAM_SERVER_BIND);
$sock = socket_import_stream($stream);
var_dump($sock);
$so = socket_set_option($sock, IPPROTO_IP, MCAST_JOIN_GROUP, array("group" => '224.0.0.23', "interface" => "lo"));
var_dump($so);
$sendsock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
var_dump($sendsock);
$br = socket_bind($sendsock, '127.0.0.1');
$so = socket_sendto($sendsock, $m = "my message", strlen($m), 0, "224.0.0.23", 58381);
var_dump($so);
stream_set_blocking($stream, 0);
var_dump(fread($stream, strlen($m)));
echo "Done.\n";
示例15: syncSendAndReceive
public function syncSendAndReceive($buffer, stdClass $context)
{
$client = $this->client;
$timeout = $context->timeout / 1000;
$sec = floor($timeout);
$usec = ($timeout - $sec) * 1000;
$trycount = 0;
$errno = 0;
$errstr = '';
while ($trycount <= 1) {
if ($this->stream === null) {
$scheme = parse_url($client->uri, PHP_URL_SCHEME);
if ($scheme == 'unix') {
$this->stream = @pfsockopen('unix://' . parse_url($client->uri, PHP_URL_PATH));
} else {
$this->stream = @stream_socket_client($client->uri, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, stream_context_create($client->options));
}
if ($this->stream === false) {
$this->stream = null;
throw new Exception($errstr, $errno);
}
}
$stream = $this->stream;
@stream_set_read_buffer($stream, $client->readBuffer);
@stream_set_write_buffer($stream, $client->writeBuffer);
if (function_exists('socket_import_stream')) {
if ($scheme === 'tcp' || $scheme === 'unix') {
$socket = socket_import_stream($stream);
socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, (int) $client->keepAlive);
if ($scheme === 'tcp') {
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $client->noDelay);
}
}
}
if (@stream_set_timeout($stream, $sec, $usec) == false) {
if ($trycount > 0) {
throw $this->getLastError("unknown error");
}
$trycount++;
} else {
break;
}
}
if ($this->write($stream, $buffer) === false) {
throw $this->getLastError("request write error");
}
$response = $this->read($stream, $buffer);
if ($response === false) {
throw $this->getLastError("response read error");
}
return $response;
}