导航菜单

Swoole与高性能开发

Swoole基础

  • Swoole简介与安装。
  • 事件驱动模型。
  • 基本配置与使用。
<?php
// Swoole基础示例

// 1. 安装Swoole
// pecl install swoole
// 或使用源码安装
// git clone https://github.com/swoole/swoole-src.git
// cd swoole-src
// phpize
// ./configure
// make && make install

// 2. 基本配置
// php.ini
extension=swoole.so

// 3. 创建HTTP服务器
$http = new Swoole\Http\Server("0.0.0.0", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://0.0.0.0:9501
";
});

$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World
");
});

$http->start();

// 4. 创建WebSocket服务器
$ws = new Swoole\WebSocket\Server("0.0.0.0", 9502);

$ws->on("open", function ($ws, $request) {
    echo "新连接: {$request->fd}
";
});

$ws->on("message", function ($ws, $frame) {
    echo "收到消息: {$frame->data}
";
    $ws->push($frame->fd, "服务器收到: {$frame->data}");
});

$ws->start();

// 5. 创建TCP服务器
$server = new Swoole\Server("0.0.0.0", 9503);

$server->on("connect", function ($server, $fd) {
    echo "新连接: {$fd}
";
});

$server->on("receive", function ($server, $fd, $reactor_id, $data) {
    echo "收到数据: {$data}
";
    $server->send($fd, "服务器收到: {$data}");
});

$server->start();
?>