### Quickstart HTTP Server Example Source: https://reactphp.org/http/index.html Sets up a basic HTTP server that responds with 'Hello World!' to all incoming requests. ```php listen($socket); ``` -------------------------------- ### Quickstart HTTP Client Example Source: https://reactphp.org/http/index.html Demonstrates sending a simple HTTP GET request to a web server and handling the response or errors. ```php get('http://www.google.com/')->then(function (Psr\Http\Message\ResponseInterface $response) { var_dump($response->getHeaders(), (string)$response->getBody()); }, function (Exception $e) { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); ``` -------------------------------- ### Quickstart HTTP Server Example Source: https://reactphp.org/http Sets up a basic HTTP server that responds with 'Hello World!' to all incoming requests. It listens on a specified local address and port. Requires the ReactPHP HTTP server, autoloader, and socket server. ```php listen($socket); ``` -------------------------------- ### Quickstart TCP Client Example Source: https://reactphp.org/socket A basic TCP client that connects to a server, pipes output to STDOUT, and sends a message. Ensure the server is running before executing. ```php $connector = new React\Socket\Connector(); $connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) { $connection->pipe(new React\Stream\WritableResourceStream(STDOUT)); $connection->write("Hello World!\n"); }, function (Exception $e) { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); ``` -------------------------------- ### Socket Server Quickstart Source: https://reactphp.org/socket A basic example of a ReactPHP socket server that writes a welcome message and closes the connection if any data is received. ```APIDOC ## Socket Server Quickstart ### Description This example demonstrates a simple socket server that sends a greeting to connected clients and immediately closes the connection if the client sends any data. ### Method N/A (This is a server setup example) ### Endpoint `127.0.0.1:8080` ### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Connection** (React\Socket\ConnectionInterface) - Represents an active connection. ### Response Example ```php $socket = new React\Socket\SocketServer('127.0.0.1:8080'); $socket->on('connection', function (React\Socket\ConnectionInterface $connection) { $connection->write("Hello " . $connection->getRemoteAddress() . "!\n"); $connection->write("Welcome to this amazing server!\n"); $connection->write("Here's a tip: don't say anything.\n"); $connection->on('data', function ($data) use ($connection) { $connection->close(); }); }); ``` ``` -------------------------------- ### Quickstart TCP Server Example Source: https://reactphp.org/socket A basic TCP server that echoes messages and closes the connection if any data is received. Requires a running server to connect to. ```php $socket = new React\Socket\SocketServer('127.0.0.1:8080'); $socket->on('connection', function (React\Socket\ConnectionInterface $connection) { $connection->write("Hello " . $connection->getRemoteAddress() . "!\n"); $connection->write("Welcome to this amazing server!\n"); $connection->write("Here's a tip: don't say anything.\n"); $connection->on('data', function ($data) use ($connection) { $connection->close(); }); }); ``` -------------------------------- ### Installation and Testing Source: https://reactphp.org/stream Commands for installing dependencies and running the test suite. ```bash composer require react/stream:^1.4 ``` ```bash composer install ``` ```bash vendor/bin/phpunit ``` ```bash vendor/bin/phpunit --exclude-group internet ``` -------------------------------- ### Socket Client Quickstart Source: https://reactphp.org/socket An example of a ReactPHP socket client that connects to a server, pipes the server's output to STDOUT, and sends a message. ```APIDOC ## Socket Client Quickstart ### Description This example demonstrates a basic socket client that connects to a specified address, streams any data received from the server to the standard output, and then sends a 'Hello World!' message to the server. ### Method N/A (This is a client connection example) ### Endpoint `127.0.0.1:8080` ### Parameters #### Query Parameters N/A ### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Connection** (React\Socket\ConnectionInterface) - Represents an active connection to the server. ### Response Example ```php $connector = new React\Socket\Connector(); $connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) { $connection->pipe(new React\Stream\WritableResourceStream(STDOUT)); $connection->write("Hello World!\n"); }, function (Exception $e) { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); ``` ``` -------------------------------- ### Install Library via Composer Source: https://reactphp.org/datagram Installs the library using Composer. ```bash composer require react/datagram:^1.10 ``` ```bash composer require react/datagram:^1.10.0 ``` -------------------------------- ### Install Project Dependencies with Composer Source: https://reactphp.org/cache To run the test suite, first clone the repository and then install all dependencies using Composer. ```bash composer install ``` -------------------------------- ### Installation Source: https://reactphp.org/event-loop Instructions for installing the ReactPHP EventLoop library using Composer. ```APIDOC ## Installation ### Description The recommended way to install this library is through Composer. This command will install the latest supported version. ### Method CLI ### Endpoint N/A ### Parameters None ### Request Example ```bash composer require react/event-loop:^1.6 ``` ### Response N/A ``` -------------------------------- ### Install ReactPHP HTTP Source: https://reactphp.org/http-client Command to install the current react/http package. ```bash composer require react/http ``` -------------------------------- ### Install ReactPHP Cache via Composer Source: https://reactphp.org/cache The recommended installation method for this library is through Composer. This command installs the latest supported version. ```bash composer require react/cache:^1.2 ``` -------------------------------- ### Quickstart: Execute a command and capture output Source: https://reactphp.org/child-process Launches a child process, listens for data on its standard output, and handles the exit event. ```php $process = new React\ChildProcess\Process('echo foo'); $process->start(); $process->stdout->on('data', function ($chunk) { echo $chunk; }); $process->on('exit', function($exitCode, $termSignal) { echo 'Process exited with code ' . $exitCode . PHP_EOL; }); ``` -------------------------------- ### Prepare and Run Test Suite Source: https://reactphp.org/http/index.html Commands to install dependencies and execute the PHPUnit test suite. ```bash composer install ``` ```bash vendor/bin/phpunit ``` ```bash vendor/bin/phpunit --exclude-group internet ``` -------------------------------- ### Initialize HttpServer with StreamingRequestMiddleware Source: https://reactphp.org/http A minimal example showing the initialization of the HttpServer with the streaming middleware. ```php $http = new React\Http\HttpServer( new React\Http\Middleware\StreamingRequestMiddleware(), ``` -------------------------------- ### Start Plaintext HTTP Server Source: https://reactphp.org/http/index.html Listen for HTTP requests on a given socket server. This example attaches the HttpServer to a SocketServer listening on 0.0.0.0:8080. ```php $http = new React\\Http\\HttpServer($handler); $socket = new React\\Socket\\SocketServer('0.0.0.0:8080'); $http->listen($socket); ``` -------------------------------- ### Install ReactPHP HTTP via Composer Source: https://reactphp.org/http/index.html Use this command to install the latest supported version of the library. ```bash composer require react/http:^1.11 ``` ```bash composer require react/http:^1.11.0 ``` -------------------------------- ### Install ReactPHP Async (specific version) Source: https://reactphp.org/async Install a specific version of ReactPHP Async using Composer. ```bash composer require react/async:^4.3.0 ``` -------------------------------- ### Install React Socket Client using Composer Source: https://reactphp.org/socket-client/changelog.html Instructions for installing the React Socket Client library version 0.7.0 using Composer. ```bash composer require react/socket-client:^0.7.0 ``` -------------------------------- ### Basic SecureServer Setup Source: https://reactphp.org/socket Instantiate a SecureServer by wrapping a TcpServer and providing basic TLS context options, including the certificate file path. ```php $server = new React\Socket\TcpServer(8000); $server = new React\Socket\SecureServer($server, null, array( 'local_cert' => 'server.pem' )); ``` -------------------------------- ### Run Test Suite Source: https://reactphp.org/datagram Commands to install dependencies and execute the test suite. ```bash composer install ``` ```bash vendor/bin/phpunit ``` -------------------------------- ### Start HTTPS Server with TLS Source: https://reactphp.org/http/index.html Configure and start an HTTPS server by attaching the HttpServer to a SocketServer with TLS options, including certificate and passphrase. ```php $http = new React\\Http\\HttpServer($handler); $socket = new React\\Socket\\SocketServer('tls://0.0.0.0:8443', array( 'tls' => array( 'local_cert' => __DIR__ . '/localhost.pem' ) )); $http->listen($socket); ``` -------------------------------- ### Install ReactPHP DNS via Composer Source: https://reactphp.org/dns Use this command to install the latest supported version of the ReactPHP DNS library. Ensure Composer is installed and accessible in your environment. ```bash composer require react/dns:^1.14 ``` -------------------------------- ### Install ReactPHP Async (multiple versions) Source: https://reactphp.org/async Install ReactPHP Async to support multiple major versions simultaneously, allowing a wider range of PHP versions. ```bash composer require "react/async:^4 || ^3 || ^2" ``` -------------------------------- ### Install ReactPHP Async (latest supported) Source: https://reactphp.org/async Install the latest supported version of ReactPHP Async using Composer. This project follows SemVer. ```bash composer require react/async:^4.3 ``` -------------------------------- ### Simplify Usage with Default Loop Source: https://reactphp.org/http/changelog.html Examples show how to simplify browser and server instantiation by utilizing the new default loop support. ```php // old (still supported) $browser = new React\Http\Browser($loop); $server = new React\Http\Server($loop, $handler); ``` ```php // new (using default loop) $browser = new React\Http\Browser(); $server = new React\Http\Server($handler); ``` -------------------------------- ### Install Composer Dependencies for Tests Source: https://reactphp.org/async Install all project dependencies using Composer before running the test suite. ```bash composer install ``` -------------------------------- ### Install ReactPHP EventLoop Source: https://reactphp.org/event-loop/license.html Use Composer to install the EventLoop library. Ensure you specify the desired version constraint. ```bash composer require react/event-loop:^1.6.0 ``` -------------------------------- ### View process hierarchy after exec Source: https://reactphp.org/child-process Example of the process tree structure when using exec. ```text 5480 … \_ php example.php 5481 … \_ yes ``` -------------------------------- ### View process hierarchy Source: https://reactphp.org/child-process Example of the process tree structure on Unix. ```text 5480 … \_ php example.php 5481 … \_ sh -c yes 5482 … \_ yes ``` -------------------------------- ### Install React Promise Timer via Composer Source: https://reactphp.org/promise-timer Install the latest supported version of the React Promise Timer library using Composer. ```bash composer require react/promise-timer:^1.11 ``` -------------------------------- ### Install React Promise using Composer (Specific Version) Source: https://reactphp.org/promise Installs the latest supported version of react/promise within the 3.2 branch. This is the recommended way to install the library for projects requiring compatibility with PHP 7.1+. ```bash composer require react/promise:^3.2 ``` -------------------------------- ### Initialize Async HTTP Client Source: https://reactphp.org/http/changelog.html Instantiate the async HTTP client to make GET requests. Ensure the loop is available. ```php $browser = new React\Http\Browser($loop); $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { echo $response->getBody(); }); ``` -------------------------------- ### Install Project Dependencies with Composer Source: https://reactphp.org/socket-client Install all project dependencies, including development tools like PHPUnit, using Composer. This is a prerequisite for running the test suite. ```bash $ composer install ``` -------------------------------- ### Run Test Suite with PHPUnit Source: https://reactphp.org/cache After installing dependencies, navigate to the project root and execute the test suite using PHPUnit. ```bash vendor/bin/phpunit ``` -------------------------------- ### HttpServer Listening Source: https://reactphp.org/http Shows how to attach the HttpServer to a SocketServer to start listening for connections. ```APIDOC ## GET /api/users/{id} ### Description Retrieves the details of a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": "user-123", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Install React Cache Source: https://reactphp.org/cache/license.html Use this command to install the React Cache component version 1.2.0 or higher. ```bash composer require react/cache:^1.2.0 ``` -------------------------------- ### Install ReactPHP Promise Stream via Composer Source: https://reactphp.org/promise-stream Install the library using Composer. This command fetches the latest supported version, ensuring compatibility with your project. ```bash composer require react/promise-stream:^1.7 ``` -------------------------------- ### Install PromiseTimer via Composer Source: https://reactphp.org/promise-timer/license.html Use this command to add the library to your project dependencies. ```bash composer require react/promise-timer:^1.11.0 ``` -------------------------------- ### Install React Promise using Composer (Multiple Major Versions) Source: https://reactphp.org/promise Installs react/promise, supporting major versions 3, 2, and 1. This allows targeting a wider range of PHP versions, from PHP 5.3+. ```bash composer require "react/promise:^3 || ^2 || ^1" ``` -------------------------------- ### Install HttpClient via Composer Source: https://reactphp.org/http-client/license.html Use this command to add the HttpClient library to your project dependencies. ```bash composer require react/http-client:^0.5.11 ``` -------------------------------- ### Activate socket via systemd Source: https://reactphp.org/socket/changelog.html Command-line example for using systemd socket activation with a PHP script. ```bash $ systemd-socket-activate -l 8000 php examples/03-http-server.php php://fd/3 ``` -------------------------------- ### Basic Async Execution with await() Source: https://reactphp.org/async Demonstrates a basic asynchronous execution flow using `async()` and `await()`. This example shows sequential output with a delay. ```php echo 'a'; await(async(static function (): void { echo 'b'; delay(2); echo 'c'; })()); echo 'd'; return time(); })(); ``` -------------------------------- ### Configure Write Buffer Soft Limit Source: https://reactphp.org/stream Example of initializing the stream with a custom write buffer soft limit. ```php $stream = new WritableResourceStream(STDOUT, null, 8192); ``` -------------------------------- ### Run test suite Source: https://reactphp.org/http-client Commands to install dependencies and execute tests, including options to exclude network-dependent tests. ```bash $ composer install ``` ```bash $ php vendor/bin/phpunit ``` ```bash $ php vendor/bin/phpunit --exclude-group internet ``` -------------------------------- ### Install ReactPHP Async Source: https://reactphp.org/async/changelog.html Use Composer to add the latest version of the ReactPHP Async component to your project. ```bash composer require react/async:^4.3.0 ``` -------------------------------- ### Configure Read Chunk Size Source: https://reactphp.org/stream Example of initializing the stream with a specific read chunk size. ```php $stream = new ReadableResourceStream(STDIN, null, 8192); ``` -------------------------------- ### Process Execution and Stream Handling Source: https://reactphp.org/child-process Demonstrates how to initialize, start, and interact with a child process using ReactPHP streams. ```APIDOC ## Process Execution ### Description Initializes and starts a child process, allowing interaction via STDIN, STDOUT, and STDERR streams. ### Usage - **Process Initialization**: `new React\ChildProcess\Process(string $command)` - **Start**: `$process->start()` - **Streams**: - `$stdin` (WritableStreamInterface): Used to write data to the process. - `$stdout` (ReadableStreamInterface): Used to read output from the process. - `$stderr` (ReadableStreamInterface): Used to read error output from the process. ### Events - **exit**: Emitted when the process terminates. Provides `$exitCode` and `$termSignal`. - **data**: Emitted by streams when new data is available. - **end**: Emitted when a stream is closed. - **error**: Emitted when an error occurs on a stream. ### Example ```php $process = new React\ChildProcess\Process('echo foo'); $process->start(); $process->stdout->on('data', function ($chunk) { echo $chunk; }); $process->on('exit', function($exitCode, $termSignal) { echo 'Process exited with code ' . $exitCode . PHP_EOL; }); ``` ``` -------------------------------- ### Configure Write Chunk Size Source: https://reactphp.org/stream Example of initializing the stream with a custom write chunk size. ```php $stream = new WritableResourceStream(STDOUT, null, null, 8192); ``` -------------------------------- ### Fallback Get and Set with ReactPHP Cache Source: https://reactphp.org/cache Fetch a cached value, and if not found, retrieve it from the database and cache it. This example demonstrates chaining for conditional caching. ```php $cache ->get('foo') ->then(function ($result) { if ($result === null) { return $this->getAndCacheFooFromDb(); } return $result; }) ->then('var_dump'); ``` ```php public function getAndCacheFooFromDb() { return $this->db ->get('foo') ->then(array($this, 'cacheFooFromDb')); } ``` ```php public function cacheFooFromDb($foo) { $this->cache->set('foo', $foo); return $foo; } ``` -------------------------------- ### Initialize Socket and Connector with Default Loop Source: https://reactphp.org/socket/changelog.html Illustrates the simplified initialization syntax that leverages the default event loop. ```php // old (still supported) $socket = new React\Socket\Server('127.0.0.1:8080', $loop); $connector = new React\Socket\Connector($loop); // new (using default loop) $socket = new React\Socket\Server('127.0.0.1:8080'); $connector = new React\Socket\Connector(); ``` -------------------------------- ### Install ReactPHP DNS via Composer Source: https://reactphp.org/dns/license.html Use this command to add the ReactPHP DNS library to your project dependencies. ```bash composer require react/dns:^1.14.0 ``` -------------------------------- ### Initialize Process with Default Loop Source: https://reactphp.org/child-process/changelog.html Demonstrates the transition from explicitly passing a loop instance to using the default loop for process management. ```php // old (still supported) $process = new React\ChildProcess\Process($command); $process->start($loop); // new (using default loop) $process = new React\ChildProcess\Process($command); $process->start(); ``` -------------------------------- ### Initialize Streaming Request Server Source: https://reactphp.org/http/index.html Basic setup for a ReactPHP HTTP server utilizing the StreamingRequestMiddleware. This snippet demonstrates the initial server configuration. ```php $http = new React\Http\HttpServer( new React\Http\Middleware\StreamingRequestMiddleware(), ``` -------------------------------- ### Install ReactPHP EventLoop via Composer Source: https://reactphp.org/event-loop Installs the latest supported version of the ReactPHP EventLoop component using Composer. This is the recommended installation method. ```bash composer require react/event-loop:^1.6 ``` -------------------------------- ### HttpServer Initialization Source: https://reactphp.org/http Demonstrates how to initialize the HttpServer with a request handler. ```APIDOC ## POST /api/users ### Description This endpoint is used to create a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the newly created user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": "user-123", "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### GET Request Source: https://reactphp.org/http/index.html Sends an HTTP GET request to the specified URL. ```APIDOC ## GET Browser::get ### Description Sends an HTTP GET request to the specified URL and returns a promise that resolves to a PSR-7 ResponseInterface. ### Parameters #### Path Parameters - **url** (string) - Required - The target URL to send the GET request to. #### Query Parameters - **headers** (array) - Optional - An associative array of HTTP headers to include in the request. ### Response #### Success Response (200) - **PromiseInterface** - A promise that resolves with the HTTP response body. ``` -------------------------------- ### Initialize Browser with Custom Connector and Loop Source: https://reactphp.org/http/index.html Initialize the React\Http\Browser with custom connector settings and an event loop. ```php $connector = new React\Socket\Connector(array( 'dns' => '127.0.0.1', 'tcp' => array( 'bindto' => '192.168.10.1:0' ), 'tls' => array( 'verify_peer' => false, 'verify_peer_name' => false ) )); $browser = new React\Http\Browser($connector); ``` -------------------------------- ### Client Initialization Source: https://reactphp.org/http-client How to instantiate the HttpClient with the event loop and optional custom connector settings. ```APIDOC ## Client Initialization ### Description Initializes the HttpClient to manage HTTP communication and connection state. ### Method Constructor ### Parameters #### Request Body - **loop** (React\EventLoop\LoopInterface) - Required - The main event loop instance. - **connector** (React\Socket\ConnectorInterface) - Optional - Custom connector for DNS, TLS, or proxy settings. ``` -------------------------------- ### Create a basic HTTP server with ReactPHP Source: https://reactphp.org This example demonstrates how to initialize a simple HTTP server that listens on port 8080 and returns a plaintext response. ```php listen($socket); echo "Server running at http://127.0.0.1:8080" . PHP_EOL; ``` -------------------------------- ### Initialize Resolver with Default Loop Source: https://reactphp.org/dns/changelog.html Demonstrates the transition from explicitly passing a loop to using the default loop for resolver creation. ```php // old (still supported) $factory = new React\Dns\Resolver\Factory(); $resolver = $factory->create($config, $loop); // new (using default loop) $factory = new React\Dns\Resolver\Factory(); $resolver = $factory->create($config); ``` -------------------------------- ### Initialize Streams with Default Loop Source: https://reactphp.org/stream/changelog.html Demonstrates the transition from explicitly passing a loop instance to using the default loop for stream initialization. ```php // old (still supported) $stream = new ReadableResourceStream($resource, $loop); $stream = new WritabeResourceStream($resource, $loop); $stream = new DuplexResourceStream($resource, $loop); // new (using default loop) $stream = new ReadableResourceStream($resource); $stream = new WritabeResourceStream($resource); $stream = new DuplexResourceStream($resource); ``` -------------------------------- ### GET / (Browser Client) Source: https://reactphp.org/http/index.html Performs an asynchronous HTTP GET request using the ReactPHP Browser client. ```APIDOC ## GET [URL] ### Description Sends an asynchronous HTTP GET request to the specified URL. ### Method GET ### Request Example $client->get('http://www.google.com/'); ### Response #### Success Response (200) - **response** (Psr\Http\Message\ResponseInterface) - The HTTP response object containing headers and body. ``` -------------------------------- ### Install RingCentral PSR-7 Dependency Source: https://reactphp.org/http/changelog.html Use this command to explicitly install the old RingCentral PSR-7 dependency if needed. ```bash composer require ringcentral/psr7 ``` -------------------------------- ### Install ReactPHP Socket Source: https://reactphp.org/socket/license.html Use Composer to install the ReactPHP Socket library. Ensure you specify the desired version. ```bash composer require react/socket:^1.17.0 ``` -------------------------------- ### Method: listen() Source: https://reactphp.org/http/index.html Attaches the HttpServer to a socket server to begin accepting incoming connections. ```APIDOC ## Method: listen() ### Description Starts listening for incoming connections by attaching the server to a socket instance. ### Parameters - **socket** (React\Socket\ServerInterface) - Required - The socket server instance to attach to. ``` -------------------------------- ### Install ReactPHP Datagram Source: https://reactphp.org/datagram/license.html Use Composer to install the ReactPHP Datagram component. Ensure you specify the desired version. ```bash composer require react/datagram:^1.10.0 ``` -------------------------------- ### Send HTTP GET Request Source: https://reactphp.org/http/index.html Send an HTTP GET request using the browser and handle the response or errors. ```php $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { var_dump((string)$response->getBody()); }, function (Exception $e) { echo 'Error: ' . $e->getMessage() . PHP_EOL; }); ``` -------------------------------- ### Establish a connection with connect() Source: https://reactphp.org/socket Use this method to initiate a streaming connection to a remote address. The returned promise handles success and failure states. ```php $connector->connect('google.com:443')->then( function (React\Socket\ConnectionInterface $connection) { // connection successfully established }, function (Exception $error) { // failed to connect due to $error } ); ``` -------------------------------- ### Establish outgoing client connections Source: https://reactphp.org/socket/changelog.html Demonstrates creating a connector and establishing an asynchronous connection to a remote host. ```php $connector = new React\Socket\Connector($loop); $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { $connection->write('…'); }); ``` -------------------------------- ### Create a basic DNS resolver Source: https://reactphp.org/dns Initializes a resolver using the system configuration and performs a basic hostname resolution. ```php $config = React\Dns\Config\Config::loadSystemConfigBlocking(); if (!$config->nameservers) { $config->nameservers[] = '8.8.8.8'; } $factory = new React\Dns\Resolver\Factory(); $dns = $factory->create($config); $dns->resolve('igor.io')->then(function ($ip) { echo "Host: $ip\n"; }); ``` -------------------------------- ### Initialize SocketServer and Deprecated Server Source: https://reactphp.org/socket/changelog.html Demonstrates the transition from the deprecated Server class to the new SocketServer class with updated constructor signatures. ```php // deprecated $socket = new React\Socket\Server(0); $socket = new React\Socket\Server('127.0.0.1:8000'); $socket = new React\Socket\Server('127.0.0.1:8000', null, $context); $socket = new React\Socket\Server('127.0.0.1:8000', $loop, $context); // new $socket = new React\Socket\SocketServer('127.0.0.1:0'); $socket = new React\Socket\SocketServer('127.0.0.1:8000'); $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context); $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context, $loop); ``` -------------------------------- ### Install ReactPHP Socket via Composer Source: https://reactphp.org/socket Use this command to install the latest supported version of the ReactPHP Socket library. This project follows SemVer. ```bash composer require react/socket:^1.17 ``` -------------------------------- ### SocketServer Initialization Source: https://reactphp.org/socket Demonstrates various ways to initialize the SocketServer for different connection types and addresses. ```APIDOC ## SocketServer Initialization ### Description This section covers the initialization of the `SocketServer` class for various network protocols and address configurations. ### Method `__construct(string $uri, array $context = [])` ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Plaintext TCP/IP $socket = new React\Socket\SocketServer('127.0.0.1:8080'); // Listen on all interfaces $socket = new React\Socket\SocketServer('0.0.0.0:8080'); // IPv6 address $socket = new React\Socket\SocketServer('[::1]:8080'); // Random port assignment $socket = new React\Socket\SocketServer('127.0.0.1:0'); $address = $socket->getAddress(); // Unix domain socket (UDS) $socket = new React\Socket\SocketServer('unix:///tmp/server.sock'); // File descriptor (FD) $socket = new React\Socket\SocketServer('php://fd/3'); // TCP socket context options $socket = new React\Socket\SocketServer('[::1]:8080', array( 'tcp' => array( 'backlog' => 200, 'so_reuseport' => true, 'ipv6_v6only' => true ) )); // Secure TLS server $socket = new React\Socket\SocketServer('tls://127.0.0.1:8080', array( 'tls' => array( 'local_cert' => 'server.pem' ) )); // TLS with passphrase $socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( 'tls' => array( 'local_cert' => 'server.pem', 'passphrase' => 'secret' ) )); // TLS with specific crypto method $socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( 'tls' => array( 'local_cert' => 'server.pem', 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER ) )); ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A ``` -------------------------------- ### Install ReactPHP Socket Client via Composer Source: https://reactphp.org/socket-client Install the latest supported version of the ReactPHP Socket Client library using Composer. This is the recommended method for integrating the library into your project. ```bash $ composer require react/socket-client:^0.7 ``` -------------------------------- ### Executing Command with Plain PHP Helper Source: https://reactphp.org/child-process This example shows how to achieve the same result as the `foobar` helper program using plain PHP, by embedding the logic directly into the command string. This avoids the need for an external helper program. ```php $code = '$s=stream_socket_client($argv[1]);do{fwrite($s,$d=fread(STDIN, 8192));}while(isset($d[0]));'; $command = 'ping example.com | php -r ' . escapeshellarg($code) . ' ' . escapeshellarg($server->getAddress()); $process = new Process($command, null, null, array()); $process->start(); ``` -------------------------------- ### Handle InvalidArgumentException Source: https://reactphp.org/stream Example of an invalid constructor argument that triggers an exception. ```php // throws InvalidArgumentException $stream = new WritableResourceStream(false); ``` -------------------------------- ### Initialize SocketServer with file descriptor Source: https://reactphp.org/socket/changelog.html Use this to listen on an existing file descriptor, which is useful for systemd socket activation. ```php $socket = new React\Socket\SocketSever('php://fd/3'); ``` -------------------------------- ### Initialize Unix domain socket servers Source: https://reactphp.org/socket/changelog.html Create a server using the unix:// URI scheme or the dedicated UnixServer class. ```php // new: Server now supports "unix://" scheme $server = new Server('unix:///tmp/server.sock', $loop); // new: advanced usage $server = new UnixServer('/tmp/server.sock', $loop); ``` -------------------------------- ### GET getLocalAddress() Source: https://reactphp.org/socket-client Retrieves the local IP address and port associated with the current connection. ```APIDOC ## GET getLocalAddress() ### Description Returns the full local address (IP and port) where the connection has been established from. This is useful for identifying which network interface (e.g., WAN vs LAN) is being used. ### Method GET ### Response - **address** (string|null) - The full local address as a string, or null if the address cannot be determined or the connection is closed. ### Request Example $address = $connection->getLocalAddress(); ### Response Example "127.0.0.1:8080" ``` -------------------------------- ### React\Http\HttpServer::listen Source: https://reactphp.org/http/index.html Starts listening for HTTP requests on the provided socket server instance. ```APIDOC ## listen(React\Socket\ServerInterface $socket) ### Description Starts listening for incoming HTTP requests on the specified socket server. This method attaches the HTTP server to the socket to process connections and parse incoming data. ### Method void ### Parameters #### Path Parameters - **socket** (React\Socket\ServerInterface) - Required - The socket server instance to listen on. ``` -------------------------------- ### Process Stream Handling Source: https://reactphp.org/child-process Demonstrates how to interact with process I/O streams (stdout, stdin) and handle stream events like 'data', 'end', 'error', and 'close'. Requires a started process. ```php $process = new Process($command); $process->start(); $process->stdout->on('data', function ($chunk) { echo $chunk; }); $process->stdout->on('end', function () { echo 'ended'; }); $process->stdout->on('error', function (Exception $e) { echo 'error: ' . $e->getMessage(); }); $process->stdout->on('close', function () { echo 'closed'; }); $process->stdin->write($data); $process->stdin->end($data = null); // … ``` -------------------------------- ### Handle RuntimeException on Windows Source: https://reactphp.org/stream Example of a scenario where non-blocking mode is not supported, resulting in a RuntimeException. ```php // throws RuntimeException on Windows $stream = new ReadableResourceStream(STDIN); ``` -------------------------------- ### Execute a basic command Source: https://reactphp.org/child-process Run a simple command line string using the Process class. ```php $process = new Process('echo test'); $process->start(); ``` -------------------------------- ### Handle Invalid Stream Resources Source: https://reactphp.org/stream Example of an invalid constructor argument that triggers an InvalidArgumentException. ```php // throws InvalidArgumentException $stream = new ReadableResourceStream(false); ``` -------------------------------- ### Unhandled Promise Rejection Source: https://reactphp.org/promise/changelog.html Example of an unhandled rejection triggering the default reporting mechanism. ```php // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 reject(new RuntimeException('Unhandled')); ``` -------------------------------- ### Install PromiseStream with Composer Source: https://reactphp.org/promise-stream/license.html Use this command to add PromiseStream version 1.7.0 to your project dependencies. ```bash composer require react/promise-stream:^1.7.0 ``` -------------------------------- ### Create an async HTTP server with EventLoop Source: https://reactphp.org/event-loop Demonstrates using the global Loop accessor to handle stream sockets and periodic timers. ```php getTimeout() . ' seconds ' . PHP_EOL; ``` -------------------------------- ### Configure Custom Connector Source: https://reactphp.org/http-client Initialize the client with custom DNS, TCP, and TLS settings via a ConnectorInterface. ```php $connector = new \React\Socket\Connector($loop, array( 'dns' => '127.0.0.1', 'tcp' => array( 'bindto' => '192.168.10.1:0' ), 'tls' => array( 'verify_peer' => false, 'verify_peer_name' => false ) )); $client = new Client($loop, $connector); ``` -------------------------------- ### Handle RuntimeException on Windows Source: https://reactphp.org/stream Example of a scenario where non-blocking mode is not supported, causing a runtime exception. ```php // throws RuntimeException on Windows $stream = new WritableResourceStream(STDOUT); ``` -------------------------------- ### Mixed Resolution and Rejection Forwarding in Promises Source: https://reactphp.org/promise Demonstrates how to mix promise resolutions and rejections, showing how handler results are forwarded predictably. This example illustrates handling a rejection and then returning a new value, which is then processed by a subsequent `then` handler. ```php $deferred = new React\Promise\Deferred(); $deferred->promise() ->then(function ($x) { return $x + 1; }) ->then(function ($x) { throw new \Exception($x + 1); }) ->catch(function (\Exception $x) { // Handle the rejection, and don't propagate. // This is like catch without a rethrow return $x->getMessage() + 1; }) ->then(function ($x) { echo 'Mixed ' . $x; }); $deferred->resolve(1); // Prints "Mixed 4" ```