### Example Source: https://github.com/swoole/docs/blob/main/public/en/thread/pool.md Example of setting up and starting a thread pool. ```php $map = new Swoole\Thread\Map(); (new Pool(TestThread::class, 4)) ->withAutoloader(__DIR__ . '/vendor/autoload.php') ->withClassDefinitionFile(__DIR__ . '/TestThread.php') ->withArguments(uniqid(), $map) ->start(); ``` -------------------------------- ### Advanced Complete Compilation Example Source: https://github.com/swoole/docs/blob/main/public/en/environment.md A more comprehensive example for downloading, compiling, and installing Swoole from the master branch with specific configuration options. ```shell mkdir -p ~/build && \ cd ~/build && \ rm -rf ./swoole-src && \ curl -o ./tmp/swoole.tar.gz https://github.com/swoole/swoole-src/archive/master.tar.gz -L && \ tar zxvf ./tmp/swoole.tar.gz && \ mv swoole-src* swoole-src && \ cd swoole-src && \ phpize && \ ./configure \ --enable-openssl --enable-sockets --enable-mysqlnd --enable-swoole-curl --enable-cares --enable-swoole-pgsql && \ sudo make && sudo make install ``` -------------------------------- ### wait() usage example Source: https://github.com/swoole/docs/blob/main/public/en/event.md Example of starting event listening with Event::wait. ```php Swoole\Timer::tick(1000, function () {\n echo "hello\n";\n});\n\nSwoole\Event::wait(); ``` -------------------------------- ### Usage Example 2: Starting a Yii program Source: https://github.com/swoole/docs/blob/main/public/en/process/process.md Shows how to start a Yii program using the exec function, emphasizing the correct format for passing arguments. ```php $process = new \Swoole\Process(function (\Swoole\Process $childProcess) { // This format is not supported // $childProcess->exec('/usr/local/bin/php /var/www/project/yii-best-practice/cli/yii t/index -m=123 abc xyz'); // Encapsulating the exec system call // Absolute path // Parameters must be separately put into an array $childProcess->exec('/usr/local/bin/php', ['/var/www/project/yii-best-practice/cli/yii', 't/index', '-m=123', 'abc', 'xyz']); // exec system call }); $process->start(); // Start the child process ``` -------------------------------- ### Development Live Preview Source: https://github.com/swoole/docs/blob/main/README.md Commands to install dependencies and start the development live preview server. ```shell # npm install -g pnpm pnpm install # with npm china mirror registry # pnpm install --registry=https://registry.npmmirror.com npm run dev ``` -------------------------------- ### Example of starting a Process Pool and handling worker events Source: https://github.com/swoole/docs/blob/main/public/en/process/process_pool.md This example demonstrates how to create a Process Pool, define callbacks for worker start and stop events, and then start the pool. The WorkerStart callback includes logic to connect to Redis and process messages from a queue. ```php $workerNum = 10; $pool = new Swoole\Process\Pool($workerNum); $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) { $msg = $redis->brpop($key, 2); if ( $msg == null) continue; var_dump($msg); } }); $pool->on("WorkerStop", function ($pool, $workerId) { echo "Worker#{$workerId} is stopped\n"; }); $pool->start(); ``` -------------------------------- ### GET Parameters Example Source: https://github.com/swoole/docs/blob/main/public/en/http_server.md Example of accessing GET parameters and dumping all GET parameters. ```php // For example: index.php?hello=123 echo $request->get['hello']; // Get all GET parameters var_dump($request->get); ``` -------------------------------- ### Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/process/process_manager.md Demonstrates how to create a Process Manager, add worker processes, and start them. ```php use Swoole\Process\Manager; use Swoole\Process\Pool; $pm = new Manager(); for ($i = 0; $i < 2; $i++) { $pm->add(function (Pool $pool, int $workerId) { }); } $pm->start(); ``` -------------------------------- ### Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/memory/table.md Example demonstrating the creation and setup of a Swoole Table. ```php $table = new Swoole\Table(1024); $table->column('id', Swoole\Table::TYPE_INT); $table->column('name', Swoole\Table::TYPE_STRING, 64); $table->column('num', Swoole\Table::TYPE_FLOAT); $table->create(); $worker = new Swoole\Process(function () {}, false, false); $worker->start(); //$serv = new Swoole\Server('127.0.0.1', 9501); //$serv->start(); ``` -------------------------------- ### Basic Http Server Source: https://github.com/swoole/docs/blob/main/public/en/http_server.md A simple example of creating and starting an Http Server. ```php $http = new Swoole\Http\Server("127.0.0.1", 9501); $http->on('request', function ($request, $response) { $response->end("

Hello Swoole. #".rand(1000, 9999)."); }); $http->start(); ``` -------------------------------- ### Compile and install from source code Source: https://github.com/swoole/docs/blob/main/public/en/environment.md Standard commands to compile and install Swoole from its source code. ```shell cd swoole-src && \ phpize && \ ./configure && \ sudo make && sudo make install ``` -------------------------------- ### getClientInfo Example Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md Example of how to use getClientInfo and its return value. ```php $fd_info = $server->getClientInfo($fd); var_dump($fd_info); ``` ```text array(15) { ["server_port"]=> int(9501) ["server_fd"]=> int(4) ["socket_fd"]=> int(25) ["socket_type"]=> int(1) ["remote_port"]=> int(39136) ["remote_ip"]=> string(9) "127.0.0.1" ["reactor_id"]=> int(1) ["connect_time"]=> int(1677322106) ["last_time"]=> int(1677322106) ["last_recv_time"]=> float(1677322106.901918) ["last_send_time"]=> float(0) ["last_dispatch_time"]=> float(0) ["close_errno"]=> int(0) ["recv_queued_bytes"]=> int(78) ["send_queued_bytes"]=> int(0) } ``` -------------------------------- ### Transaction Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/mysql.md A simple example illustrating how to start a transaction using `begin()`, execute a query, and then commit the transaction. ```php $db->begin(); $db->query("update userinfo set level = 22 where id = 1"); $db->commit(); ``` -------------------------------- ### Compile Swoole with OpenSSL support Source: https://github.com/swoole/docs/blob/main/public/en/question/install.md Example of enabling OpenSSL support during Swoole compilation using PECL. ```shell enable openssl support? [no] : yes --with-openssl-dir=/opt/openssl/ ``` -------------------------------- ### Compile Swoole with specific PHP paths Source: https://github.com/swoole/docs/blob/main/public/en/question/install.md Example of using absolute paths for phpize and php-config when PHP versions mismatch. ```shell /usr/local/php-5.4.17/bin/phpize ./configure --with-php-config=/usr/local/php-5.4.17/bin/php-config /usr/local/php-5.4.17/bin/php server.php ``` -------------------------------- ### Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md An example demonstrating how to use the command() method to call custom commands and retrieve process information. ```php addCommand('test_getpid', SWOOLE_SERVER_COMMAND_MASTER | SWOOLE_SERVER_COMMAND_EVENT_WORKER, function ($server, $data) { var_dump($data); return json_encode(['pid' => posix_getpid()]); }); $server->set([ 'log_file' => '/dev/null', 'worker_num' => 2, ]); $server->on('start', function (Server $serv) { $result = $serv->command('test_getpid', 0, SWOOLE_SERVER_COMMAND_MASTER, ['type' => 'master']); Assert::eq($result['pid'], $serv->getMasterPid()); $result = $serv->command('test_getpid', 1, SWOOLE_SERVER_COMMAND_EVENT_WORKER, ['type' => 'worker']); Assert::eq($result['pid'], $serv->getWorkerPid(1)); $result = $serv->command('test_not_found', 1, SWOOLE_SERVER_COMMAND_EVENT_WORKER, ['type' => 'worker']); Assert::false($result); $serv->shutdown(); }); $server->on('request', function (Request $request, Response $response) { }); $server->start(); ``` -------------------------------- ### Running a Swoole Server Source: https://github.com/swoole/docs/blob/main/public/en/start/start_server.md This command shows how to execute a PHP file containing Swoole server code from the command line. ```shell php /path/to/your_file.php ``` -------------------------------- ### PECL Installation with Custom Options Source: https://github.com/swoole/docs/blob/main/public/en/environment.md Example of installing Swoole via PECL with specific configuration options enabled or disabled. ```shell pecl install -D 'enable-sockets="no" enable-openssl="yes" enable-http2="yes" enable-mysqlnd="yes" enable-swoole-json="no" enable-swoole-curl="yes" enable-cares="yes"' swoole ``` ```shell pecl install --configureoptions 'enable-sockets="no" enable-openssl="yes" enable-http2="yes" enable-mysqlnd="yes" enable-swoole-json="no" enable-swoole-curl="yes" enable-cares="yes"' swoole ``` -------------------------------- ### Complete Example Source: https://github.com/swoole/docs/blob/main/public/en/client.md A basic example demonstrating how to create a Swoole\Client, connect to a server, send data, receive a response, and close the connection. ```php $client = new Swoole\Client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9501, -1)) { exit("connect failed. Error: {$client->errCode}\n"); } $client->send("hello world\n"); echo $client->recv(); $client->close(); ``` -------------------------------- ### Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/http_client.md Example demonstrating the usage of get(), post(), and request() functions. ```php use function Swoole\Coroutine\go; use function Swoole\Coroutine\run; use function Swoole\Coroutine\Http\get; use function Swoole\Coroutine\Http\post; use function Swoole\Coroutine\Http\request; run(function () { go(function () { $data = get('http://httpbin.org/get?hello=world'); $body = json_decode($data->getBody()); assert($body->headers->Host === 'httpbin.org'); assert($body->args->hello === 'world'); }); go(function () { $random_data = base64_encode(random_bytes(128)); $data = post('http://httpbin.org/post?hello=world', ['random_data' => $random_data]); $body = json_decode($data->getBody()); assert($body->headers->Host === 'httpbin.org'); assert($body->args->hello === 'world'); assert($body->form->random_data === $random_data); }); }); ``` -------------------------------- ### __construct() Example Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md Example usage of the Swoole Server __construct() method and addlistener(). ```php $server = new \Swoole\Server($host, $port = 0, $mode = SWOOLE_PROCESS, $sockType = SWOOLE_SOCK_TCP); // Can mix UDP/TCP, listen on internal and external ports, see addlistener section for multi-port listening. $server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP); // Add TCP $server->addlistener("192.168.1.100", 9503, SWOOLE_SOCK_TCP); // Add Web Socket $server->addlistener("0.0.0.0", 9504, SWOOLE_SOCK_UDP); // UDP $server->addlistener("/var/run/myserv.sock", 0, SWOOLE_UNIX_STREAM); // UnixSocket Stream $server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP | SWOOLE_SSL); // TCP + SSL $port = $server->addListener("0.0.0.0", 0, SWOOLE_SOCK_TCP); // System randomly assigns a port, returned value is the randomly assigned port echo $port->port; ``` -------------------------------- ### statvfs() Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine/system.md Example of how to use the statvfs() method to get file system information. ```php Swoole\Coroutine\run(function () { var_dump(Swoole\Coroutine\System::statvfs('/')); }); // array(11) { // ["bsize"]=> // int(4096) // ["frsize"]=> // int(4096) // ["blocks"]=> // int(61068098) // ["bfree"]=> // int(45753580) // ["bavail"]=> // int(42645728) // ["files"]=> // int(15523840) // ["ffree"]=> // int(14909927) // ["favail"]=> // int(14909927) // ["fsid"]=> // int(1002377915335522995) // ["flag"]=> // int(4096) // ["namemax"]=> // int(255) // } ``` -------------------------------- ### Example Source: https://github.com/swoole/docs/blob/main/public/en/server/port.md An example demonstrating how to create an HTTP/WebSocket server and then listen on an additional native TCP port. ```php $http_server = new Swoole\Http\Server('0.0.0.0', 9998); $http_server->set(['daemonize' => false]); $http_server->on('request', function ($request, $response) { $response->header("Content-Type", "text/html; charset=utf-8"); $response->end("

Hello Swoole. #" . rand(1000, 9999) . "

"); }); // Listen to an additional TCP port, provide TCP service externally, and set a callback for the TCP server $tcp_server = $http_server->listen('0.0.0.0', 9999, SWOOLE_SOCK_TCP); // The newly listened port 9999 will inherit the settings of the main server by default, also using the HTTP protocol. // Need to call the set method to override the settings of the main server $tcp_server->set([]); $tcp_server->on('receive', function ($server, $fd, $threadId, $data) { echo $data; }); $http_server->start(); ``` -------------------------------- ### pack Example Source: https://github.com/swoole/docs/blob/main/public/en/websocket_server.md An example demonstrating how to use the pack method to send a "hello world" message to a WebSocket client. ```php $ws = new Swoole\Server('127.0.0.1', 9501 , SWOOLE_BASE); $ws->set(array( 'log_file' => '/dev/null' )); $ws->on('WorkerStart', function (\Swoole\Server $serv) { }); $ws->on('receive', function ($serv, $fd, $threadId, $data) { $sendData = "HTTP/1.1 101 Switching Protocols\r\n"; $sendData .= "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: IFpdKwYy9wdo4gTldFLHFh3xQE0=\r\n"; $sendData .= "Sec-WebSocket-Version: 13\r\nServer: swoole-http-server\r\n\r\n"; $sendData .= Swoole\WebSocket\Server::pack("hello world\n"); $serv->send($fd, $sendData); }); $ws->start(); ``` -------------------------------- ### Example usage of swoole_cpu_num() Source: https://github.com/swoole/docs/blob/main/public/en/functions.md An example demonstrating how to use swoole_cpu_num to get the number of CPU cores. ```shell php -r "echo swoole_cpu_num();" ``` -------------------------------- ### start() Method Signature Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md The signature of the start() method for the Swoole Server. ```php Swoole\Server->start(): bool ``` -------------------------------- ### Example usage of swoole_get_local_ip() Source: https://github.com/swoole/docs/blob/main/public/en/functions.md An example demonstrating how to use swoole_get_local_ip to get local IP addresses. ```php // Get the IP addresses of all network interfaces on the local machine $list = swoole_get_local_ip(); print_r($list); /** Returned value Array ( [eno1] => 10.10.28.228 [br-1e72ecd47449] => 172.20.0.1 [docker0] => 172.17.0.1 ) **/ ``` -------------------------------- ### Example usage of swoole_version() Source: https://github.com/swoole/docs/blob/main/public/en/functions.md An example demonstrating how to use swoole_version to get the Swoole extension version. ```php var_dump(SWOOLE_VERSION); // The global variable SWOOLE_VERSION also represents the Swoole extension version var_dump(swoole_version()); /** Returns: string(6) "1.9.23" string(6) "1.9.23" **/ ``` -------------------------------- ### set() Example Source: https://github.com/swoole/docs/blob/main/public/ja/server/methods.md Example of setting various operational parameters for the server. ```php $server->set(array( 'reactor_num' => 2, // スレッド数 'worker_num' => 4, // プロセス数 'backlog' => 128, // Listenキューの長さを設定 'max_request' => 50, // 各プロセスが受け入れる最大リクエスト数 'dispatch_mode' => 1, // データパケットの配布戦略 )); ``` -------------------------------- ### metaData() Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/postgresql-old.md Example of how to use the metaData method to get table information. ```php use Swoole\Coroutine\PostgreSQL; use function Swoole\Coroutine\run; run(function () { $pg = new PostgreSQL(); $conn = $pg->connect("host=127.0.0.1 port=5432 dbname=test user=wuzhenyu"); $result = $pg->metaData('test'); var_dump($result); }); ``` -------------------------------- ### Basic GET Request Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/http_client.md An example of making a GET request to httpbin.org and echoing the response body. ```php use Swoole\Coroutine\Http\Client; use function Swoole\Coroutine\run; run(function () { $cli = new Client('httpbin.org', 80); $cli->get('/get'); echo $cli->body; $cli->close(); }); ``` -------------------------------- ### set() Example Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md Example usage of the Swoole Server set() method to configure server parameters. ```php $server->set(array( 'reactor_num' => 2, // number of threads 'worker_num' => 4, // number of processes 'backlog' => 128, // set the length of the listen queue 'max_request' => 50, // maximum number of requests per process 'dispatch_mode' => 1, // data packet dispatch strategy )); ``` -------------------------------- ### Example Usage of heartbeat() Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md An example demonstrating how to use the heartbeat() method to get an array of closed connection file descriptors. ```php $closeFdArrary = $server->heartbeat(); ``` -------------------------------- ### Start a full coroutine HTTP service Source: https://github.com/swoole/docs/blob/main/public/en/coroutine/scheduler.md Example of starting a coroutine HTTP server using Swoole\Coroutine\Http\Server and Coroutine\run(). ```php use Swoole\Coroutine\Http\Server; use function Swoole\Coroutine\run; run(function () { $server = new Server('127.0.0.1', 9502, false); $server->handle('/', function ($request, $response) { $response->end("

Index

"); }); $server->handle('/test', function ($request, $response) { $response->end("

Test

"); }); $server->handle('/stop', function ($request, $response) use ($server) { $response->end("

Stop

"); $server->shutdown(); }); $server->start(); }); echo 1;//won't be executed ``` -------------------------------- ### addlistener Example Source: https://github.com/swoole/docs/blob/main/public/ja/server/methods.md Example demonstrating how to add listeners for UDP/TCP, internal and external ports, and multiple ports. ```php $server = new \Swoole\Server($host, $port = 0, $mode = SWOOLE_PROCESS, $sockType = SWOOLE_SOCK_TCP); // UDP/TCPを混在して使用し、内網と外網のポートを同時に监听し、多ポート监听については addlistener 小節を参照してください。 $server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP); // TCPを追加 $server->addlistener("192.168.1.100", 9503, SWOOLE_SOCK_TCP); // Web Socketを追加 $server->addlistener("0.0.0.0", 9504, SWOOLE_SOCK_UDP); // UDPを追加 $server->addlistener("/var/run/myserv.sock", 0, SWOOLE_UNIX_STREAM); // UnixSocket Streamを追加 $server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP | SWOOLE_SSL); // TCP + SSLを追加 $port = $server->addListener("0.0.0.0", 0, SWOOLE_SOCK_TCP); // システムがランダムに割り当てるポート番号を戻し、ランダムに割り当てられたポート番号を返します。 echo $port->port; ``` -------------------------------- ### Usage Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/redis.md Basic example of connecting to a Redis server and getting a value using the Coroutine Redis Client. ```php use Swoole\Coroutine\Redis; use function Swoole\Coroutine\run; run(function () { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $val = $redis->get('key'); }); ``` -------------------------------- ### MQTT Server Example Source: https://github.com/swoole/docs/blob/main/public/en/start/start_mqtt.md This code demonstrates how to set up a basic MQTT server using Swoole. It includes functions for decoding MQTT values and strings, parsing MQTT headers, and handling connect and receive events. The server is configured to enable the MQTT protocol. ```php function decodeValue($data) { return 256 * ord($data[0]) + ord($data[1]); } function decodeString($data) { $length = decodeValue($data); return substr($data, 2, $length); } function mqttGetHeader($data) { $byte = ord($data[0]); $header['type'] = ($byte & 0xF0) >> 4; $header['dup'] = ($byte & 0x08) >> 3; $header['qos'] = ($byte & 0x06) >> 1; $header['retain'] = $byte & 0x01; return $header; } function eventConnect($header, $data) { $connect_info['protocol_name'] = decodeString($data); $offset = strlen($connect_info['protocol_name']) + 2; $connect_info['version'] = ord(substr($data, $offset, 1)); $offset += 1; $byte = ord($data[$offset]); $connect_info['willRetain'] = ($byte & 0x20 == 0x20); $connect_info['willQos'] = ($byte & 0x18 >> 3); $connect_info['willFlag'] = ($byte & 0x04 == 0x04); $connect_info['cleanStart'] = ($byte & 0x02 == 0x02); $offset += 1; $connect_info['keepalive'] = decodeValue(substr($data, $offset, 2)); $offset += 2; $connect_info['clientId'] = decodeString(substr($data, $offset)); return $connect_info; } $server = new Swoole\Server('127.0.0.1', 9501, SWOOLE_BASE); $server->set([ 'open_mqtt_protocol' => true, // Enable MQTT protocol 'worker_num' => 1, ]); $server->on('Connect', function ($server, $fd) { echo "Client:Connect.\n"; }); $server->on('Receive', function ($server, $fd, $reactor_id, $data) { $header = mqttGetHeader($data); var_dump($header); if ($header['type'] == 1) { $resp = chr(32) . chr(2) . chr(0) . chr(0); eventConnect($header, substr($data, 2)); $server->send($fd, $resp); } elseif ($header['type'] == 3) { $offset = 2; $topic = decodeString(substr($data, $offset)); $offset += strlen($topic) + 2; $msg = substr($data, $offset); echo "client msg: {$topic}\n----------\n{$msg}\n"; //file_put_contents(__DIR__.'/data.log', $data); } echo "received length=" . strlen($data) . "\n"; }); $server->on('Close', function ($server, $fd) { echo "Client: Close.\n"; }); $server->start(); ``` -------------------------------- ### Complete Example Source: https://github.com/swoole/docs/blob/main/public/en/client_async.md An example demonstrating the usage of Swoole\Async\Client for connecting, sending, receiving, and closing a connection. ```php $cli = new Swoole\Async\Client(SWOOLE_SOCK_TCP); $client->on("connect", function(Swoole\Async\Client $client) { Assert::true($client->isConnected()); $client->send(RandStr::gen(1024, RandStr::ALL)); }); $client->on("receive", function(Swoole\Async\Client $client, string $data){ $recv_len = strlen($data); $client->send(RandStr::gen(1024, RandStr::ALL)); $client->close(); Assert::false($client->isConnected()); }); $client->on("error", function(Swoole\Async\Client $client) { echo "error"; }); $client->on("close", function(Swoole\Async\Client $client) { echo "close"; }); $client->connect("127.0.0.1", 9501, 0.2); ``` -------------------------------- ### getClientList() Example Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md An example demonstrating how to use getClientList to iterate through client connections and send a broadcast message. ```php $start_fd = 0; while (true) { $conn_list = $server->getClientList($start_fd, 10); if ($conn_list === false || count($conn_list) === 0) { echo "finish\n"; break; } $start_fd = end($conn_list); var_dump($conn_list); foreach ($conn_list as $fd) { $server->send($fd, "broadcast"); } } ``` -------------------------------- ### statvfs() Usage Example Source: https://github.com/swoole/docs/blob/main/public/zh-Hant/coroutine/system.md Example demonstrating how to use Swoole\Coroutine\System::statvfs to get file system information for the root directory. ```php Swoole\Coroutine\run(function () { var_dump(Swoole\Coroutine\System::statvfs('/')); }); ``` -------------------------------- ### Example of addProcess Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md An example demonstrating how to add a user-defined process that broadcasts messages received via a unixSocket to all server connections. The process implements a broadcast function, looping to receive messages and sending them to all connections of the server. ```php $server = new Swoole\Server('127.0.0.1', 9501); /** * The user process implements a broadcast function, looping to receive messages from unixSocket and sending to all connections of the server */ $process = new Swoole\Process(function ($process) use ($server) { $socket = $process->exportSocket(); while (true) { $msg = $socket->recv(); foreach ($server->connections as $conn) { $server->send($conn, $msg); } } }, false, 2, 1); $server->addProcess($process); $server->on('receive', function ($serv, $fd, $reactor_id, $data) use ($process) { // Broadcast the received message $socket = $process->exportSocket(); $socket->send($data); }); $server->start(); ``` -------------------------------- ### Query Example - Return Insert ID Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/postgresql-old.md Example of executing an INSERT query with a RETURNING clause to get the inserted ID. ```php use Swoole\Coroutine\PostgreSQL; use function Swoole\Coroutine\run; run(function () { $pg = new PostgreSQL(); $conn = $pg->connect("host=127.0.0.1 port=5432 dbname=test user=wuzhenyu password="); $result = $pg->query("insert into test (id,text) VALUES (24,'text') RETURNING id ;"); $arr = $pg->fetchRow($result); var_dump($arr); }); ``` -------------------------------- ### get() Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/http_client.md Shows how to initiate a GET request to a specified URL path. This method overrides any request method set by setMethod. ```php use Swoole\Coroutine\Http\Client; use function Swoole\Coroutine\run; run(function () { $client = new Client('127.0.0.1', 80); $client->setHeaders([ 'Host' => 'localhost', 'User-Agent' => 'Chrome/49.0.2587.3', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]); $client->get('/index.php'); echo $client->body; $client->close(); }); ``` -------------------------------- ### connect event callback example Source: https://github.com/swoole/docs/blob/main/public/en/client_async.md Example of the 'connect' event callback. ```php $client->on("connect", function(Swoole\Async\Client $client) { Assert::true($client->isConnected()); }); ``` -------------------------------- ### Swoole Table Example Source: https://github.com/swoole/docs/blob/main/public/ja/memory/table.md A complete example demonstrating the creation and usage of a Swoole Table for storing connection-related information, including setting and getting data. ```php column('fd', Swoole\Table::TYPE_INT); $table->column('reactor_id', Swoole\Table::TYPE_INT); $table->column('data', Swoole\Table::TYPE_STRING, 64); $table->create(); $serv = new Swoole\Server('127.0.0.1', 9501); $serv->set(['dispatch_mode' => 1]); $serv->table = $table; $serv->on('receive', function ($serv, $fd, $reactor_id, $data) { $cmd = explode(" ", trim($data)); //get if ($cmd[0] == 'get') { //get self if (count($cmd) < 2) { $cmd[1] = $fd; } $get_fd = intval($cmd[1]); $info = $serv->table->get($get_fd); $serv->send($fd, var_export($info, true)."\n"); } //set elseif ($cmd[0] == 'set') { $ret = $serv->table->set($fd, array('reactor_id' => $data, 'fd' => $fd, 'data' => $cmd[1])); if ($ret === false) { $serv->send($fd, "ERROR\n"); } else { $serv->send($fd, "OK\n"); } } else { $serv->send($fd, "command error.\n"); } }); $serv->start(); ``` -------------------------------- ### Server->setting Property Example Source: https://github.com/swoole/docs/blob/main/public/en/server/properties.md Demonstrates how to set and access server settings using the $setting property. ```php Swoole\Server->setting ``` ```php $server = new Swoole\Server('127.0.0.1', 9501); $server->set(array ('worker_num' => 4)); echo $server->setting['worker_num']; ``` -------------------------------- ### redirect() example Source: https://github.com/swoole/docs/blob/main/public/en/http_server.md Example demonstrating how to use the redirect method. ```php $http = new Swoole\Http\Server("0.0.0.0", 9501, SWOOLE_BASE); $http->on('request', function ($req, Swoole\Http\Response $resp) { $resp->redirect("http://www.baidu.com/", 301); }); $http->start(); ``` -------------------------------- ### on() method example Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md An example demonstrating how to use the on() method to register event callbacks for a Swoole Server. ```php $server = new Swoole\Server("127.0.0.1", 9501); $server->on('connect', function ($server, $fd){ echo "Client:Connect.\n"; }); $server->on('receive', function ($server, $fd, $reactor_id, $data) { $server->send($fd, 'Swoole: '.$data); $server->close($fd); }); $server->on('close', function ($server, $fd) { echo "Client: Close.\n"; }); $server->start(); ``` -------------------------------- ### errCode Property Example Source: https://github.com/swoole/docs/blob/main/public/en/client.md Shows how to use socket_strerror to get a human-readable error message from the errCode. ```php Swoole\Client->errCode: int ``` ```php echo socket_strerror($client->errCode); ``` -------------------------------- ### Example: HTTP server with an additional TCP port Source: https://github.com/swoole/docs/blob/main/public/zh-Hant/server/port.md This demonstrates creating an HTTP server and then using `listen` to add a separate TCP port, showing how to configure the new port's protocol and callbacks. ```php $http_server = new Swoole\Http\Server('0.0.0.0',9998); $http_server->set(['daemonize'=> false]); $http_server->on('request', function ($request, $response) { $response->header("Content-Type", "text/html; charset=utf-8"); $response->end("

Hello Swoole. #".rand(1000, 9999)."."); }); //多监听一个TCP端口,对外开启TCP服务,并设置TCP服务器的回调 $tcp_server = $http_server->listen('0.0.0.0', 9999, SWOOLE_SOCK_TCP); //默认新监听的端口 9999 会继承主服务器的设置,也是 HTTP 协议 //需要调用 set 方法覆盖主服务器的设置 $tcp_server->set([]); $tcp_server->on('receive', function ($server, $fd, $threadId, $data) { echo $data; }); $http_server->start(); ``` -------------------------------- ### getBackTrace() Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine/coroutine.md Illustrates how to get the coroutine function call stack. ```php Swoole\Coroutine::getBackTrace(int $cid = 0, int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, int $limit = 0): array ``` ```php function test1() { test2(); } function test2() { while(true) { Co::sleep(10); echo __FUNCTION__." \n"; } } \Co\run(function () { $cid = go(function () { test1(); }); go(function () use ($cid) { while(true) { echo "BackTrace[$cid]:\n-----------------------------------------------\n"; // Returns an array, needs to be manually formatted for output var_dump(Co::getBackTrace($cid))."\n"; Co::sleep(3); } }); }); Swoole\Event::wait(); ``` -------------------------------- ### Complete Coroutine Server Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine/server.md A complete example demonstrating how to set up a coroutine server using Swoole, handling connections, and sending/receiving data. ```php use Swoole\Process; use Swoole\Coroutine; use Swoole\Coroutine\Server\Connection; // Multi-process management module $pool = new Process\Pool(2); // Automatically create a coroutine for each OnWorkerStart callback $pool->set(['enable_coroutine' => true]); $pool->on('workerStart', function ($pool, $id) { // Each process listens on port 9501 $server = new Swoole\Coroutine\Server('127.0.0.1', 9501, false, true); // Shutdown service when receiving signal 15 Process::signal(SIGTERM, function () use ($server) { $server->shutdown(); }); // Receive new connection requests and automatically create a coroutine $server->handle(function (Connection $conn) { while (true) { // Receive data $data = $conn->recv(1); if ($data === '' || $data === false) { $errCode = swoole_last_error(); $errMsg = socket_strerror($errCode); echo "errCode: {$errCode}, errMsg: {$errMsg}\n"; $conn->close(); break; } // Send data $conn->send('hello'); Coroutine::sleep(1); } }); // Start listening on the port $server->start(); }); $pool->start(); ``` -------------------------------- ### numRows() Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/postgresql-old.md Demonstrates how to get the number of rows from a PostgreSQL query result. ```php Swoole\Coroutine\PostgreSQL->numRows(resource $queryResult): int ``` -------------------------------- ### Complete Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine/http_server.md A complete example demonstrating the usage of Swoole\Coroutine\Http\Server. ```php use Swoole\Coroutine\Http\Server; use function Swoole\Coroutine\run; run(function () { $server = new Server('127.0.0.1', 9502, false); $server->handle('/', function ($request, $response) { $response->end("

Index

"); }); $server->handle('/test', function ($request, $response) { $response->end("

Test

"); }); $server->handle('/stop', function ($request, $response) use ($server) { $response->end("

Stop

"); $server->shutdown(); }); $server->start(); }); ``` -------------------------------- ### Connect Examples Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/client.md Examples showing how to connect to a TCP server by IP address and port, and how to connect to a Unix socket. ```php if ($cli->connect('127.0.0.1', 9501)) { $cli->send('data'); } else { echo 'connect failed.'; } if ($cli->connect('/tmp/rpc.sock')) { $cli->send('data'); } else { echo 'connect failed.'; } ``` -------------------------------- ### Constructor and Basic Usage Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/http_client.md Example demonstrating the constructor for creating an HTTP client and making a GET request. ```php use Swoole\Coroutine\Http\Client; use function Swoole\Coroutine\run; run(function () { $client = new Client('127.0.0.1', 80); $client->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(); }); ``` -------------------------------- ### SSL Client Example Source: https://github.com/swoole/docs/blob/main/public/en/client.md An example demonstrating how to configure and connect an SSL client with various certificate verification options. ```php $client = new Swoole\Client(SWOOLE_SOCK_TCP | SWOOLE_SSL); $client->set(array( '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', )); if (!$client->connect('127.0.0.1', 9501, -1)) { exit("connect failed. Error: {$client->errCode}\n"); } echo "connect ok\n"; $client->send("hello world-" . str_repeat('A', $i) . "\n"); echo $client->recv(); ``` -------------------------------- ### Add a task to the scheduler Source: https://github.com/swoole/docs/blob/main/public/en/coroutine/scheduler.md Example of adding a task (coroutine) to the scheduler using the add() method and then starting the scheduler. ```php use Swoole\Coroutine; $scheduler = new Coroutine\Scheduler; $scheduler->add(function ($a, $b) { Coroutine::sleep(1); echo assert($a == 'hello') . PHP_EOL; echo assert($b == 12345) . PHP_EOL; echo "Done.\n"; }, "hello", 12345); $scheduler->start(); ``` -------------------------------- ### confirm() - Example Usage Source: https://github.com/swoole/docs/blob/main/public/en/server/methods.md An example demonstrating how to use the confirm() method in conjunction with enable_delay_receive. ```php // Create a Server object, listen on 127.0.0.1:9501 $serv = new Swoole\Server("127.0.0.1", 9501); $serv->set([ 'enable_delay_receive' => true, ]); // Listen for connection events $serv->on('Connect', function ($serv, $fd) { // Check $fd here and confirm if okay $serv->confirm($fd); }); // Listen for data receive events $serv->on('Receive', function ($serv, $fd, $reactor_id, $data) { $serv->send($fd, "Server: " . $data); }); // Listen for connection close events $serv->on('Close', function ($serv, $fd) { echo "Client: Close.\n"; }); // Start the server $serv->start(); ``` -------------------------------- ### Prepare and Execute Example Source: https://github.com/swoole/docs/blob/main/public/en/coroutine_client/postgresql.md Example demonstrating the use of `prepare` and `execute` for prepared statements. ```php use Swoole\Coroutine\PostgreSQL; use function Swoole\Coroutine\run; run(function () { $pg = new PostgreSQL(); $conn = $pg->connect("host=127.0.0.1 port=5432 dbname=test user=wuzhenyu password=112"); $stmt = $pg->prepare("select * from test where id > $1 and id < $2"); $res = $stmt->execute(array(1, 3)); $arr = $stmt->fetchAll(); var_dump($arr); }); ``` -------------------------------- ### WaitGroup Usage Example Source: https://github.com/swoole/docs/blob/main/public/de/coroutine/wait_group.md This example demonstrates how to use WaitGroup to manage multiple coroutines. It starts two coroutines that make HTTP requests to Taobao and Baidu respectively. The WaitGroup ensures that the main coroutine waits for both requests to complete before proceeding. ```php add(); // Start the first coroutine Coroutine::create(function () use ($wg, &$result) { // Start a coroutine client to request the homepage of Taobao $cli = new Client('www.taobao.com', 443, true); $cli->setHeaders([ 'Host' => 'www.taobao.com', 'User-Agent' => 'Chrome/49.0.2587.3', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]); $cli->set(['timeout' => 1]); $cli->get('/index.php'); $result['taobao'] = $cli->body; $cli->close(); $wg->done(); }); $wg->add(); // Start the second coroutine Coroutine::create(function () use ($wg, &$result) { // Start a coroutine client to request the homepage of Baidu $cli = new Client('www.baidu.com', 443, true); $cli->setHeaders([ 'Host' => 'www.baidu.com', 'User-Agent' => 'Chrome/49.0.2587.3', 'Accept' => 'text/html,application/xhtml+xml,application/xml', 'Accept-Encoding' => 'gzip', ]); $cli->set(['timeout' => 1]); $cli->get('/index.php'); $result['baidu'] = $cli->body; $cli->close(); $wg->done(); }); // Suspend the current coroutine and wait for all tasks to complete before resuming $wg->wait(); // Here $result contains the execution results of 2 tasks var_dump($result); }); ```