### 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('