### GRPC Server Setup and Usage Source: https://openswoole.com/docs/grpc/server This example demonstrates how to initialize and start an Open Swoole GRPC server, register services, configure worker context, and apply middleware. ```APIDOC ## GRPC Server Setup ### Description This section outlines the steps and provides an example for setting up a GRPC server using Open Swoole in PHP. It covers service registration, worker context configuration, middleware addition, and server startup. ### Method `OpenSwoole\GRPC\Server` ### Endpoint N/A (Server-side implementation) ### Parameters #### Constructor - **host** (string) - The IP address to bind the server to. - **port** (int) - The port number to listen on. #### Methods - `register(string $serviceClass)`: Registers a GRPC service class. - `withWorkerContext(string $key, callable $factory)`: Sets up worker context for services. - `addMiddleware(OpenSwoole\GRPC\Middleware $middleware)`: Adds a middleware to the server. - `set(array $options)`: Configures server options. - `start()`: Starts the GRPC server. ### Request Example ```php OpenSwoole\Runtime::HOOK_ALL]); $server = (new Server('127.0.0.1', 9501)) ->register(GreeterService::class) ->register(StreamService::class) ->withWorkerContext('worker_start_time', function () { return time(); }) // use middlewares ->addMiddleware(new LoggingMiddleware()) ->addMiddleware(new TraceMiddleware()) ->set([ 'log_level' => \OpenSwoole\Constant::LOG_INFO, ]) ->start(); ``` ### Response N/A (Server-side implementation) ``` -------------------------------- ### Example Usage of Server Start Source: https://openswoole.com/docs/modules/swoole-server-start A basic example demonstrating how to create an OpenSwoole server instance, register essential event callbacks (connect, receive, close), and start the server. ```PHP on('connect', function ($server, $fd) { echo "New connection established: #{$fd}.\n"; }); $server->on('receive', function ($server, $fd, $from_id, $data) { $server->send($fd, "Echo to #{$fd}: \n" . $data); $server->close($fd); }); $server->on('close', function ($server, $fd) { echo "Connection closed: #{$fd}.\n"; }); $server->start(); ?> ``` -------------------------------- ### Start OpenSwoole Server Source: https://openswoole.com/docs/modules/swoole-server-start This example demonstrates how to initialize an OpenSwoole server, register essential event callbacks for connection, reception, and closure, and then start the server to listen for incoming requests. Ensure all necessary callbacks are registered before calling start. ```php on('connect', function ($server, $fd) { echo "New connection established: #{$fd}.\n"; }); $server->on('receive', function ($server, $fd, $from_id, $data) { $server->send($fd, "Echo to #{$fd}: \n" . $data); $server->close($fd); }); $server->on('close', function ($server, $fd) { echo "Connection closed: #{$fd}.\n"; }); $server->start(); ``` -------------------------------- ### Complete OpenSwoole WebSocket Server Example Source: https://openswoole.com/docs/modules/swoole-websocket-server-on-message This example demonstrates a basic OpenSwoole WebSocket server setup, including handling 'Start', 'Open', 'Message', and 'Close' events. It shows how to send messages back to clients and use timers. ```php on("Start", function(Server $server) { echo "OpenSwoole WebSocket Server started at 127.0.0.1:9501\n"; }); $server->on('Open', function(Server $server, OpenSwoole\Http\Request $request) { echo "connection open: {$request->fd}\n"; $server->tick(1000, function() use ($server, $request) { $server->push($request->fd, json_encode(["hello", time()])); }); }); $server->on('Message', function(Server $server, Frame $frame) { echo "received message: {$frame->data}\n"; $server->push($frame->fd, json_encode(["hello", time()])); }); $server->on('Close', function(Server $server, int $fd) { echo "connection close: {$fd}\n"; }); $server->start(); ``` -------------------------------- ### OpenSwoole Server Connection Handling Example Source: https://openswoole.com/docs/modules/swoole-server-on-connect A complete example demonstrating how to set up an OpenSwoole server and handle 'Start', 'Shutdown', 'Connect', 'Receive', and 'Close' events. The 'Connect' event handler logs new connections. ```php on('Start', function ($server) { echo "Server has started.\n"; }); $server->on('Shutdown', function ($server) { echo "Server is shutting down.\n"; }); // The onConnect event receives the server object, client fd and reactor process ID $server->on('Connect', function (OpenSwoole\Server $server, int $fd, int $reactorId) { echo "New connection established: #{$fd}.\n"; }); $server->on('Receive', function ($server, $fd, $fromId, $data) { $server->send($fd, "Echo to #{$fd}: \n" . $data); $server->close($fd); }); $server->on('Close', function ($server, $fd) { echo "Connection closed: #{$fd}.\n"; }); $server->start(); ``` -------------------------------- ### Registering the 'Start' Event Callback Source: https://openswoole.com/docs/modules/swoole-server-on-start This snippet demonstrates how to set up a callback function for the 'Start' event in OpenSwoole. The callback is executed once the server has successfully started and is ready to listen for incoming connections. It also includes examples for 'Connect', 'Receive', and 'Close' events for a complete server setup. ```php on('Start', function ($server) { echo "Server has started.\n"; }); $server->on('Connect', function ($server, $fd) { echo "New connection established: #{$fd}.\n"; }); $server->on('Receive', function ($server, $fd, $fromId, $data) { $server->send($fd, "Echo to #{$fd}: \n" . $data); $server->close($fd); }); $server->on('Close', function ($server, $fd) { echo "Connection closed: #{$fd}.\n"; }); $server->start(); ``` -------------------------------- ### Start the Open Swoole Server Source: https://openswoole.com/docs/modules/swoole-server-doc Starts the Open Swoole server, making it ready to accept connections. This should be the last step after configuration and event setup. ```php start(); ``` -------------------------------- ### GRPC Server Setup (PHP) Source: https://openswoole.com/docs/grpc Sets up and starts a GRPC server using Open Swoole in PHP. ```APIDOC ## GRPC Server Setup ### Description Sets up and starts a GRPC server using Open Swoole in PHP. ### Server Configuration ```php OpenSwoole\Runtime::HOOK_ALL]); $server = (new Server('127.0.0.1', 9501)) ->register(GreeterService::class) ->register(StreamService::class) ->withWorkerContext('worker_start_time', function () { return time(); }) // use middlewares ->addMiddleware(new LoggingMiddleware()) ->addMiddleware(new TraceMiddleware()) ->set([ 'log_level' => \OpenSwoole\Constant::LOG_INFO, ]) ->start(); ``` ``` -------------------------------- ### Full Example Source: https://openswoole.com/docs/modules/swoole-async-http2-client Demonstrates setting headers and cookies, sending both GET and POST requests, and closing the client connection. ```APIDOC ```php "www.google.com", "accept-encoding" => "gzip, deflate", 'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'accept-language' => 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,ja;q=0.2', 'user-agent' => 'Mozilla/5.0 (X11; Linux x86_64) Chrome/58.0.3026.3 Safari/537.36', ); $client = new OpenSwoole\HTTP2\Client("www.google.com", 443, true); $client->setHeaders($array); $client->setCookies(array("a" => "1", "b" => "2")); $client->get("/", function ($o) use($client) { echo "#{$client->sock} hello world 1\n"; echo $o->body; }); $client->post("/", $array, function ($o) use($client) { echo "{$client->sock} hello world 3\n"; echo $o->body; $client->close(); }); Swoole\Event::wait(); ?> ``` ``` -------------------------------- ### Full Example: Process Pool with Listen and Worker Logic Source: https://openswoole.com/docs/modules/swoole-process-pool-listen A complete example showing the creation of a process pool, defining worker start and stop events, and binding the pool to a TCP socket before starting it. The worker logic includes connecting to Redis and processing messages from a queue. ```php on("WorkerStart", function ($pool, $workerId) { echo "Worker#{$workerId} is started\n"; $redis = new Redis(); $redis->pconnect('127.0.0.1', 6379); $key = "key1"; while (true) { $msgs = $redis->brpop($key, 2); if ( $msgs == null) continue; var_dump($msgs); } }); $pool->on("WorkerStop", function ($pool, $workerId) { echo "Worker#{$workerId} is stopped\n"; }); $pool->listen('127.0.0.1', 8089); $pool->start(); ``` -------------------------------- ### Setting OpenSwoole Server Configurations Source: https://openswoole.com/docs/modules/swoole-server-set This example demonstrates how to set common runtime configurations for an OpenSwoole server. Ensure these settings are applied before calling `$server->start()`. ```php $server->set([ 'reactor_num' => 2, 'worker_num' => 4, 'backlog' => 128, 'max_request' => 50, 'dispatch_mode' => 1, ]); ``` -------------------------------- ### Basic HTTP2 Client Example Source: https://openswoole.com/docs/modules/swoole-coroutine-http2-client Demonstrates setting up a basic HTTP/2 client, configuring a timeout, connecting to a server, and sending a GET request with custom headers and cookies. Ensure the server is listening on the specified host and port. ```php set(['timeout' => 2]); // Try and connect to the remote host $client->connect(); // Create and build a request that will be sent... $request = new OpenSwoole\Http2\Request(); $request->path = "/index.php"; $request->headers = [ 'host' => "localhost", "user-agent" => 'Chrome/49.0.2587.3', 'accept' => 'text/html,application/xhtml+xml,application/xml', 'accept-encoding' => 'gzip', ]; // Add cookies to the request $request->cookies = ['name' => 'hello', 'email' => 'a@b.com']; // Send and receive a response and output the result var_dump($client->send($request)); $response = $client->recv(); var_dump($response); }); ``` -------------------------------- ### OpenSwoole WebSocket Server Example Source: https://openswoole.com/docs/modules/swoole-websocket-server-on-open This example demonstrates setting up a WebSocket server with 'Start', 'Open', 'Message', and 'Close' event handlers. The 'Open' event handler logs the connection and uses a timer to push data to the client. The 'Message' handler echoes received messages, and 'Close' logs disconnections. ```php on("Start", function(Server $server) { echo "OpenSwoole WebSocket Server started at 127.0.0.1:9501\n"; }); $server->on('Open', function(Server $server, OpenSwoole\Http\Request $request) { echo "connection open: {$request->fd}\n"; $server->tick(1000, function() use ($server, $request) { $server->push($request->fd, json_encode(["hello", time()])); }); }); $server->on('Message', function(Server $server, Frame $frame) { echo "received message: {$frame->data}\n"; $server->push($frame->fd, json_encode(["hello", time()])); }); $server->on('Close', function(Server $server, int $fd) { echo "connection close: {$fd}\n"; }); $server->start(); ``` -------------------------------- ### Start OpenSwoole WebSocket Server Source: https://openswoole.com/docs/modules/swoole-websocket-server-start This snippet demonstrates the complete setup and startup of an Open Swoole WebSocket server. It includes definitions for 'Start', 'Open', 'Message', and 'Close' event callbacks, and initiates the server to listen on 127.0.0.1:9501. The 'Open' event callback uses a 'tick' function to periodically push data to connected clients. ```php on("Start", function(Server $server) { echo "OpenSwoole WebSocket Server started at 127.0.0.1:9501\n"; }); $server->on('Open', function(Server $server, OpenSwoole\Http\Request $request) { echo "connection open: {$request->fd}\n"; $server->tick(1000, function() { $server->push($request->fd, json_encode(["hello", time()])); }); }); $server->on('Message', function(Server $server, Frame $frame) { echo "received message: {$frame->data}\n"; $server->push($frame->fd, json_encode(["hello", time()])); }); $server->on('Close', function(Server $server, int $fd) { echo "connection close: {$fd}\n"; }); $server->start(); ``` -------------------------------- ### GRPC Client Pool Usage Example Source: https://openswoole.com/docs/grpc/client-pool Demonstrates how to initialize and use the GRPC Client Pool for managing client connections. It shows creating a pool, getting connections, making gRPC calls, and returning connections to the pool. The example also includes logic for measuring performance and closing the pool. ```php \OpenSwoole::Constant::LOG_ERROR]); co::run(function () { $connpool = new ClientPool(ClientFactory::class, ['host' => '127.0.0.1', 'port' => 9501], 16); $now = microtime(true); $i = 16; $total = 100_000; while ($i-- > 0) { $conn = $connpool->get(); go(function () use ($conn, $connpool, $now, &$total, $i) { $client = new Helloworld\GreeterClient($conn); $message = new HelloRequest(); $message->setName(str_repeat('x', 100)); while (1) { $total--; $out = $client->sayHello($message); if ($total <= 0) { var_dump($out->serializeToJsonString()); echo (int) (100_000 / (microtime(true) - $now)) . "\n"; break; } } $connpool->put($conn); echo "DONE {$i}\n"; }); } go(function () use ($connpool) { // try to close after 1 second co::sleep(1); $connpool->close(); echo "CLOSE\n"; }); }); ``` -------------------------------- ### Creating HTTP Client with Direct IP and Port Source: https://openswoole.com/docs/modules/swoole-coroutine-http-client-construct This example shows how to instantiate an HTTP client using a direct IP address and port. It sets custom headers and a timeout before executing a GET request to a specific path. ```php setHeaders([ 'Host' => 'localhost', 'User-Agent' => 'Chrome/49.0.2587.3', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]); $client->set(['timeout' => 1]); $client->get('/index.php'); echo $client->body; $client->close(); }); ``` -------------------------------- ### Install Open Swoole via Docker Source: https://openswoole.com/docs/get-started/installation Pull the official Open Swoole Docker image. This is a quick way to get started in a containerized environment. ```bash docker pull openswoole/swoole ``` -------------------------------- ### Basic HTTP Server Setup with Configuration Source: https://openswoole.com/docs/modules/swoole-http-server/configuration Demonstrates how to initialize an OpenSwoole HTTP server and apply common configuration options like worker numbers and temporary upload directory. ```php set([ 'worker_num' => 2, 'task_worker_num' => 2, 'upload_tmp_dir' => '/data/uploaded_files/', // ... ]); $server->on('Request', function(OpenSwoole\Http\Request $request, OpenSwoole\Http\Response $response) { // On Request event callback... }); $server->start(); ``` -------------------------------- ### Server Initialization Example Source: https://openswoole.com/docs/modules/swoole-server-construct Demonstrates how to create a new OpenSwoole Server instance with default or custom parameters, and how to add multiple listeners for different protocols and ports. ```PHP addlistener("127.0.0.1", 9502, OpenSwoole\Constant::SOCK_TCP); // TCP listener $server->addlistener("192.168.1.100", 9503, OpenSwoole\Constant::SOCK_TCP); // Web Socket listener $server->addlistener("0.0.0.0", 9504, OpenSwoole\Constant::SOCK_UDP); // UDP listener $server->addlistener("/var/run/myserv.sock", 0, OpenSwoole\Constant::UNIX_STREAM); // UnixSocket Stream $server->addlistener("127.0.0.1", 9502, OpenSwoole\Constant::SOCK_TCP | OpenSwoole\Constant::SSL); //TCP + SSL // Because port is set to 0, a random port is used $port = $server->addListener("0.0.0.0", 0, OpenSwoole\Constant::SOCK_TCP); // See which port was selected echo $port->port; ?> ``` -------------------------------- ### Get GRPC Service Name Source: https://openswoole.com/docs/grpc/service-container-get-name Use this method to retrieve the name of the GRPC service. No specific setup or imports are required beyond having the Open Swoole extension installed. ```php getName() ``` -------------------------------- ### Get GRPC Request Method Source: https://openswoole.com/docs/grpc/request-get-method Use this method to retrieve the HTTP method of the incoming GRPC request. No specific setup or imports are required beyond having the Open Swoole extension installed. ```php getMethod() ``` -------------------------------- ### Start the Open Swoole HTTP Server Source: https://openswoole.com/docs/modules/swoole-http-server-doc Execute the `start()` method to launch the HTTP server. This should be the last step after setting up the server instance, configuration, and event callbacks. Run the script using `php server.php`. ```php start(); ``` -------------------------------- ### Start Server Source: https://openswoole.com/docs/modules/swoole-server-doc Start the Open Swoole server to begin accepting connections. ```APIDOC ## Start Server ### Description Start the Open Swoole server process. ### Method `OpenSwoole\Server->start` ### Request Example ```php start(); ``` ``` -------------------------------- ### Resume Coroutine Execution by ID Source: https://openswoole.com/docs/modules/swoole-coroutine-resume This example demonstrates how to start a coroutine, get its ID, and then resume its execution multiple times using OpenSwoole\Coroutine::resume. The coroutine yields control, waits for resumption, and prints messages at each stage. ```php setHeaders([ 'Host' => 'localhost', 'User-Agent' => 'Chrome/49.0.2587.3', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]); // First GET request $client->get('/home/contact'); var_dump($client->body); // Second GET request $client->get('/index.php'); var_dump($client->body); $client->close(); }); ``` -------------------------------- ### Full SSL Client Configuration Example Source: https://openswoole.com/docs/modules/swoole-client-overall-config-set-options An example demonstrating a comprehensive SSL client configuration, including certificate files, verification options, and passphrase. ```php set([ 'ssl_cert_file' => __DIR__.'/ca/client-cert.pem', 'ssl_key_file' => __DIR__.'/ca/client-key.pem', 'ssl_allow_self_signed' => true, 'ssl_verify_peer' => true, 'ssl_cafile' => __DIR__.'/ca/ca-cert.pem', 'ssl_passphrase' => '********', ]); if(!$client->connect('127.0.0.1', 9501, -1)) { exit("Connection failed: {$client->errCode} "); } echo "Connection OK\n"; $client->send("Hello World! " . str_repeat('A', $i) . "\n"); echo $client->recv(); ``` -------------------------------- ### Basic OpenSwoole HTTP Server Setup Source: https://openswoole.com/docs/modules/swoole-http-server-working-example This snippet demonstrates the fundamental setup of an OpenSwoole HTTP server. It includes initializing the server, setting worker and task worker counts, and defining the main request handler to send a 'Hello World!' response. Configure the server's IP address and port as needed. ```php set([ 'worker_num' => 4, // The number of worker processes to start 'task_worker_num' => 4 // The amount of task workers to start 'backlog' => 128, // TCP backlog connection number ]); // Triggered when new worker processes starts $server->on("WorkerStart", function($server, $workerId) { echo "Worker Started: $workerId\n"; }); // Triggered when the HTTP Server starts, connections are accepted after this callback is executed $server->on("Start", function($server, $workerId) { echo "OpenSwoole HTTP Server Started @ 127.0.0.1:8501\n"; }); // The main HTTP server request callback event, entry point for all incoming HTTP requests $server->on('Request', function(OpenSwoole\Server\Request $request, OpenSwoole\Server\Response $response) { $response->end('

Hello World!

'); }); // Triggered when the server is shutting down $server->on("Shutdown", function($server, $workerId) { echo "Server shutting down...\n"; }); // Triggered when worker processes are being stopped $server->on("WorkerStop", function($server, $workerId) { echo "Worker Stopped: $workerId\n"; }); $server->start(); ?> ``` -------------------------------- ### Process Pool Start Event Handler Source: https://openswoole.com/docs/modules/swoole-process-pool-on-start Execute custom logic when the Process Pool is started. This is useful for global setup tasks before any workers begin their execution. ```php on('start', function() { echo "Process Pool is started\n"; }); $pool->on("WorkerStart", function ($pool, $workerId) { echo "Worker#{$workerId} is started\n"; $redis = new Redis(); $redis->pconnect('127.0.0.1', 6379); $key = "key1"; while (true) { $msgs = $redis->brpop($key, 2); if ( $msgs == null) continue; var_dump($msgs); } }); $pool->on("WorkerStop", function ($pool, $workerId) { echo "Worker#{$workerId} is stopped\n"; }); $pool->start(); ``` -------------------------------- ### Install Open Swoole on Ubuntu/Debian via PPA (Repeat) Source: https://openswoole.com/docs/get-started/installation This section appears to be a duplicate of the previous Ubuntu/Debian PPA installation instructions. ```bash apt update apt install -y software-properties-common && add-apt-repository ppa:openswoole/ppa -y # choose one PHP version: #apt install -y php7.4-openswoole #apt install -y php8.0-openswoole apt install -y php8.1-openswoole ``` -------------------------------- ### WaitGroup done() Usage Example Source: https://openswoole.com/docs/modules/swoole-coroutine-waitgroup-done This example demonstrates how to use `WaitGroup->done()` to signal the completion of coroutines. Ensure the OpenSwoole core library is installed via composer. ```php add(); co::sleep(3); $wg->done(); }); go(function () use ($wg) { $wg->add(); co::sleep(7); $wg->done(); }); $wg->wait(1); }); ``` -------------------------------- ### Example Usage of MysqliConfig Source: https://openswoole.com/docs/core/coroutine-client-mysqli-config Demonstrates how to instantiate and configure a MysqliConfig object using the provided methods. ```PHP withHost('localhost'); // Verify the host has been set var_dump($config->getHost() === 'localhost'); // Configure other parameters (example) $config->withPort(3306) ->withDbname('mydatabase') ->withUsername('myuser') ->withPassword('mypassword') ->withCharset('utf8mb4'); // Retrieve and dump configured values var_dump($config->getPort()); var_dump($config->getDbname()); var_dump($config->getUsername()); var_dump($config->getPassword()); var_dump($config->getCharset()); ?> ``` -------------------------------- ### OpenSwoole\Core\Process\Manager->start() Source: https://openswoole.com/docs/modules/swoole-process-manager-start Starts the OpenSwoole process manager. This method is essential for launching and managing child processes within the OpenSwoole framework. Ensure the OpenSwoole core library is installed via composer. ```APIDOC ## OpenSwoole\Core\Process\Manager->start() ### Description Starts the OpenSwoole process manager. ### Method `start()` ### Parameters None ### Return None ### Usage Example ```php add(function (OpenSwoole\Process\Pool $pool, int $workerId) use ($atomic) { usleep(100000); $atomic->wakeup(); }); $pm->add(function (OpenSwoole\Process\Pool $pool, int $workerId) use ($atomic) { $atomic->wait(1.5); $pool->shutdown(); }); $pm->start(); ``` ``` -------------------------------- ### Client Configuration Defaults Example Source: https://openswoole.com/docs/modules/swoole-coroutine-http-client-set This example demonstrates setting various configuration options for an HTTP client, including method, reconnect attempts, timeout, defer, keep-alive, WebSocket mask and compression, HTTP compression, and body decompression. ```php set([ 'method' => 'GET', 'reconnect' => 1, 'timeout' => 0.5, 'defer' => false, 'keep_alive' => true, 'websocket_mask' => true, 'websocket_compression' => false, 'http_compression' => false, 'body_decompression' => true, ]); ``` -------------------------------- ### Helloworld GreeterClient Example Source: https://openswoole.com/docs/grpc/client This code defines a GreeterClient class that extends \OpenSwoole\GRPC\BaseStub. It includes a SayHello method for making RPC calls. ```php _simpleRequest('/helloworld.Greeter/SayHello', $request, ['\Helloworld\HelloReply', 'decode'], $metadata); } } ``` -------------------------------- ### Add Function to Process Manager Example Source: https://openswoole.com/docs/modules/swoole-process-manager-add This example demonstrates how to use the `add` method to execute functions within processes. It utilizes an `Atomic` object for synchronization between processes and shows how to start and shut down the process manager. ```php add(function (Pool $pool, int $workerId) use ($atomic) { usleep(100000); $atomic->wakeup(); }); $pm->add(function (Pool $pool, int $workerId) use ($atomic) { $atomic->wait(1.5); $pool->shutdown(); }); $pm->start(); ``` -------------------------------- ### Connect to Redis and Set a Key Source: https://openswoole.com/docs/modules/swoole-async-redis-client Example demonstrating how to connect to a Redis server asynchronously and set a key-value pair using a callback. ```php connect('127.0.0.1', 6379, function (swoole_redis $client, $result) { if ($result === false) { echo "connect to redis server failed." return; } $client->set('key', 'swoole', function (swoole_redis $client, $result) { var_dump($result); }); }); ``` -------------------------------- ### Get OpenSwoole Version Source: https://openswoole.com/docs/modules/swoole-util-get-version Call the static `getVersion` method on the `OpenSwoole\Util` class to retrieve the installed OpenSwoole version. ```php begin(function( $db, $result) { $db->query("update userinfo set level = 22 where id = 1", function($db, $result) { $db->rollback(function($db, $result) { echo "commit ok\n"; }); }); }); ``` -------------------------------- ### HTTP2 Client GET Request Callback Example Source: https://openswoole.com/docs/modules/swoole-async-http2-client Defines the callback function structure for processing HTTP2 responses from a GET request. It shows how to access response properties like cookies, headers, server information, body, and status code. ```php cookie); var_dump($resp->header); var_dump($resp->server); var_dump($resp->body); var_dump($resp->statusCode); } ``` -------------------------------- ### OpenSwoole WebSocket Server Implementation Example Source: https://openswoole.com/docs/modules/swoole-websocket-server-push A complete example demonstrating how to set up an OpenSwoole WebSocket server, handle connections, and use the `push` method to send messages to clients. ```php on("Start", function(Server $server) { echo "OpenSwoole WebSocket Server is started at 127.0.0.1:9501\n"; }); $server->on('Open', function(Server $server, OpenSwoole\Http\Request $request) { echo "connection open: {$request->fd}\n"; $server->tick(1000, function() use ($server, $request) { $server->push($request->fd, json_encode(["hello", time()])); }); }); $server->on('Message', function(Server $server, Frame $frame) { echo "received message: {$frame->data}\n"; $server->push($frame->fd, json_encode(["hello", time()])); }); $server->on('Close', function(Server $server, int $fd) { echo "connection close: {$fd}\n"; }); $server->start(); ``` -------------------------------- ### Example Usage of PDOConfig Source: https://openswoole.com/docs/core/coroutine-client-pdo-config Demonstrates how to instantiate PDOConfig and set the host. ```PHP withHost('localhost'); var_dump($config->getHost() === 'localhost'); ?> ``` -------------------------------- ### Get IPC Type of Process Manager Source: https://openswoole.com/docs/modules/swoole-process-manager-getIPCType This is the declaration for the getIPCType method. You must install the OpenSwoole core library to use this feature. ```php getIPCType() ``` -------------------------------- ### TCP/UDP Server Setup Source: https://openswoole.com/docs/modules/swoole-server-doc This snippet shows how to instantiate a new Open Swoole TCP server, specifying the host, port, mode, and socket type. ```APIDOC ## TCP/UDP Server Setup ### Description Instantiate a new Open Swoole TCP server. ### Method `OpenSwoole\Server::__construct` ### Parameters - **host** (string) - The IP address or hostname to bind to. - **port** (int) - The port number to listen on. - **mode** (int) - The server mode (e.g., `OpenSwoole\Server::SIMPLE_MODE`). - **sock_type** (int) - The socket type (e.g., `OpenSwoole\Constant::SOCK_TCP`). ### Request Example ```php getMethods() ``` -------------------------------- ### General Example Source: https://openswoole.com/docs/modules/swoole-coroutine-postgres A basic example demonstrating how to connect to a PostgreSQL database and execute a query using the Coroutine PostgreSQL client. ```APIDOC ## General Example ```php connect("host=127.0.0.1;port=5432;dbname=test;user=postgres;password=***"); if(!$conn) { var_dump($pg->error); return; } $result = $pg->query('SELECT * FROM test;'); $arr = $pg->fetchAll($result); var_dump($arr); }); ``` ``` -------------------------------- ### Retrieve Server Parameters with getServerParams Source: https://openswoole.com/docs/psr/psr-server-request-get-server-params Call this method to get all server parameters. No specific setup is required beyond having an instance of ServerRequest. ```php getServerParams() ``` -------------------------------- ### Get Server Request Attributes in PHP Source: https://openswoole.com/docs/psr/psr-server-request-get-attributes Use this method to retrieve attributes that have been derived from the request. Ensure Open Swoole is installed and configured. ```php getAttributes() ``` -------------------------------- ### Connect to Server and Send Data with OpenSwoole Client Source: https://openswoole.com/docs/modules/swoole-client-connect Use this example to connect to a specified host and port using the OpenSwoole Client. It demonstrates checking the connection status and sending data if the connection is successful. Ensure the client is properly initialized before use. ```php connect('127.0.0.1', 9501)) { $cli->send("data"); } else { echo "connect failed."; } ``` -------------------------------- ### OpenSwoole\Process Constructor and Basic Usage Source: https://openswoole.com/docs/modules/swoole-process Demonstrates how to create a new OpenSwoole\Process, define its execution logic, start the process, and communicate with it using write and read operations. ```APIDOC ## OpenSwoole\Process::__construct ### Description Initializes a new OpenSwoole\Process object. The constructor accepts a callback function that defines the child process's behavior and an optional boolean to indicate if the process should be a daemon. ### Method `__construct(callable $callback, bool $daemon = false, int $pipe_type = 1, bool $enable_coroutine = false)` ### Parameters - **`$callback`** (callable) - The function to be executed by the child process. - **`$daemon`** (bool) - If true, the process will run as a daemon. - **`$pipe_type`** (int) - Type of pipe to use for IPC (e.g., `1` for unix socket). - **`$enable_coroutine`** (bool) - If true, enables coroutine support within the child process. ## OpenSwoole\Process->start ### Description Starts the execution of the child process. ### Method `start(): bool` ### Return Value Returns `true` on success, `false` on failure. ## OpenSwoole\Process->write ### Description Writes data to the pipe of the child process. This is typically used by the parent process to send data to the child. ### Method `write(string $data): bool` ### Parameters - **`$data`** (string) - The data to write. ### Return Value Returns `true` on success, `false` on failure. ## OpenSwoole\Process->read ### Description Reads data from the pipe of the child process. This is typically used by the parent process to receive data from the child. ### Method `read(int $length = 8192): string` ### Parameters - **`$length`** (int) - The maximum number of bytes to read. ### Return Value Returns the data read from the pipe, or `false` on failure. ### Request Example ```php pid . "\n"; echo "the file descriptor of pipe is " . $worker->pipe . "\n"; $res = $worker->write("Hello main process\n"); var_dump(strlen("Hello main process\n")); var_dump($res); $worker->name("php child process"); }, FALSE); $process->start(); usleep(100); echo $process->read(); ?> ``` ``` -------------------------------- ### Get All Context Data - OpenSwoole GRPC Source: https://openswoole.com/docs/grpc/context-get-values Use this method to retrieve all associated context data. Ensure Open Swoole is installed and configured for gRPC. ```php getValues() ``` -------------------------------- ### Get MySQL Port - MysqliConfig Source: https://openswoole.com/docs/core/coroutine-client-mysqli-config-get-port Use this method to retrieve the configured port for the MySQL connection. No specific setup is required beyond having an instance of MysqliConfig. ```php getPort() ``` -------------------------------- ### Retrieve URI User Information with OpenSwoole Source: https://openswoole.com/docs/psr/psr-uri-get-user-info Use this method to get the user information part of a URI. No specific setup is required beyond having an OpenSwooleuri object. ```php getUserInfo() ``` -------------------------------- ### Compile and Install Open Swoole from Source Source: https://openswoole.com/docs/get-started/installation Manually compile and install Open Swoole from its GitHub repository. This involves cloning the repo, checking out a specific version, configuring build options, and then compiling. ```bash #!/bin/bash # Install git to access the source code from GitHub $ sudo apt install git $ cd /tmp && git clone https://github.com/openswoole/ext-openswoole.git && \ cd ext-openswoole && \ git checkout v26.2.0 && \ phpize && \ ./configure --enable-openssl \ --enable-mysqlnd \ --enable-sockets \ --enable-http2 \ --enable-hook-curl \ --with-postgres \ --enable-cares && \ sudo make && sudo make install ``` -------------------------------- ### Get Hostname from URI - OpenSwoole Source: https://openswoole.com/docs/psr/psr-uri-get-host Use this method to retrieve the hostname component of a URI object. No specific setup is required beyond having an instance of the Uri class. ```php getHost() ``` -------------------------------- ### Simple Sync TCP Client Example Source: https://openswoole.com/docs/modules/swoole-client A basic example demonstrating how to create and use a synchronous TCP client with Open Swoole. ```APIDOC ## Simple Sync TCP Client ### Description A simple sync TCP client. ### Example ```php connect('127.0.0.1', 9501, -1)) { exit("connect failed. Error: {$client->errCode}\n"); } $client->send("hello world\n"); echo $client->recv(); $client->close(); ``` ``` -------------------------------- ### Get HTTP Protocol Version Source: https://openswoole.com/docs/psr/psr-response-get-protocol-version Use this method to retrieve the HTTP protocol version from the response object. No specific setup is required beyond having a response object. ```php getProtocolVersion() ```