GithubHelp home page GithubHelp logo

swoole / swoole-src Goto Github PK

View Code? Open in Web Editor NEW
18.2K 831.0 3.2K 50.43 MB

🚀 Coroutine-based concurrency library for PHP

Home Page: https://www.swoole.com

License: Apache License 2.0

CMake 0.13% C 3.10% Shell 0.21% M4 0.70% PHP 36.39% Python 0.05% C++ 59.33% PLpgSQL 0.07% Go 0.01% JavaScript 0.01% Makefile 0.01%
swoole coroutines php websocket event concurrency

swoole-src's Introduction

Swoole Logo
Swoole is an event-driven, asynchronous, coroutine-based concurrency library with high performance for PHP.

lib-swoole ext-swoole test-linux Frameworks Tests codecov

Twitter Discord Latest Release License Coverity Scan Build Status

⚙️ Quick Start

Run Swoole program by Docker

docker run --rm phpswoole/swoole "php --ri swoole"

For details on how to use it, see: How to Use This Image.

Documentation

https://wiki.swoole.com/

HTTP Service

$http = new Swoole\Http\Server('127.0.0.1', 9501);
$http->set(['hook_flags' => SWOOLE_HOOK_ALL]);

$http->on('request', function ($request, $response) {
    $result = [];
    Co::join([
        go(function () use (&$result) {
            $result['google'] = file_get_contents("https://www.google.com/");
        }),
        go(function () use (&$result) {
            $result['taobao'] = file_get_contents("https://www.taobao.com/");
        })
    ]);
    $response->end(json_encode($result));
});

$http->start();

Concurrency

Co\run(function() {
    Co\go(function() {
        while(1) {
            sleep(1);
            $fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
            echo fread($fp, 8192), PHP_EOL;
        }
    });

    Co\go(function() {
        $fp = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
        while(1) {
            $conn = stream_socket_accept($fp);
            fwrite($conn, 'The local time is ' . date('n/j/Y g:i a'));
        }
    });

    Co\go(function() {
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        while(true) {
            $redis->subscribe(['test'], function ($instance, $channelName, $message) {
                echo 'New redis message: '.$channelName, "==>", $message, PHP_EOL;
            });
        }
    });

    Co\go(function() {
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
        $count = 0;
        while(true) {
            sleep(2);
            $redis->publish('test','hello, world, count='.$count++);
        }
    });
});

Runtime Hook

Swoole hooks the blocking io function of PHP at the bottom layer and automatically converts it to a non-blocking function, so that these functions can be called concurrently in coroutines.

Supported extension/functions

  • ext-curl (Support symfony and guzzle)
  • ext-redis
  • ext-mysqli
  • ext-pdo_mysql
  • ext-pdo_pgsql
  • ext-pdo_sqlite
  • ext-pdo_oracle
  • ext-pdo_odbc
  • stream functions (e.g. stream_socket_client/stream_socket_server), Supports TCP/UDP/UDG/Unix/SSL/TLS/FileSystem API/Pipe
  • ext-sockets
  • ext-soap
  • sleep/usleep/time_sleep_until
  • proc_open
  • gethostbyname/shell_exec/exec
  • fread/fopen/fsockopen/fwrite/flock

🛠 Develop & Discussion

💎 Awesome Swoole

Project Awesome Swoole maintains a curated list of awesome things related to Swoole, including

  • Swoole-based frameworks and libraries.
  • Packages to integrate Swoole with popular PHP frameworks, including Laravel, Symfony, Slim, and Yii.
  • Books, videos, and other learning materials about Swoole.
  • Debugging, profiling, and testing tools for developing Swoole-based applications.
  • Coroutine-friendly packages and libraries.
  • Other Swoole related projects and resources.

✨ Event-based

The network layer in Swoole is event-based and takes full advantage of the underlying epoll/kqueue implementation, making it really easy to serve millions of requests.

Swoole 4.x uses a brand new engine kernel and now it has a full-time developer team, so we are entering an unprecedented period in PHP history which offers a unique possibility for rapid evolution in performance.

⚡ Coroutine

Swoole 4.x or later supports the built-in coroutine with high availability, and you can use fully synchronized code to implement asynchronous performance. PHP code without any additional keywords, the underlying automatic coroutine-scheduling.

Developers can understand coroutines as ultra-lightweight threads, and you can easily create thousands of coroutines in a single process.

MySQL

Concurrency 10K requests to read data from MySQL takes only 0.2s!

$s = microtime(true);
Co\run(function() {
    for ($c = 100; $c--;) {
        go(function () {
            $mysql = new Swoole\Coroutine\MySQL;
            $mysql->connect([
                'host' => '127.0.0.1',
                'user' => 'root',
                'password' => 'root',
                'database' => 'test'
            ]);
            $statement = $mysql->prepare('SELECT * FROM `user`');
            for ($n = 100; $n--;) {
                $result = $statement->execute();
                assert(count($result) > 0);
            }
        });
    }
});
echo 'use ' . (microtime(true) - $s) . ' s';

Mixed server

You can create multiple services on the single event loop: TCP, HTTP, Websocket and HTTP2, and easily handle thousands of requests.

function tcp_pack(string $data): string
{
    return pack('N', strlen($data)) . $data;
}
function tcp_unpack(string $data): string
{
    return substr($data, 4, unpack('N', substr($data, 0, 4))[1]);
}
$tcp_options = [
    'open_length_check' => true,
    'package_length_type' => 'N',
    'package_length_offset' => 0,
    'package_body_offset' => 4
];
$server = new Swoole\WebSocket\Server('127.0.0.1', 9501, SWOOLE_BASE);
$server->set(['open_http2_protocol' => true]);
// http && http2
$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
    $response->end('Hello ' . $request->rawcontent());
});
// websocket
$server->on('message', function (Swoole\WebSocket\Server $server, Swoole\WebSocket\Frame $frame) {
    $server->push($frame->fd, 'Hello ' . $frame->data);
});
// tcp
$tcp_server = $server->listen('127.0.0.1', 9502, SWOOLE_TCP);
$tcp_server->set($tcp_options);
$tcp_server->on('receive', function (Swoole\Server $server, int $fd, int $reactor_id, string $data) {
    $server->send($fd, tcp_pack('Hello ' . tcp_unpack($data)));
});
$server->start();

Coroutine clients

Whether you DNS query or send requests or receive responses, all of these are scheduled by coroutine automatically.

go(function () {
    // http
    $http_client = new Swoole\Coroutine\Http\Client('127.0.0.1', 9501);
    assert($http_client->post('/', 'Swoole Http'));
    var_dump($http_client->body);
    // websocket
    $http_client->upgrade('/');
    $http_client->push('Swoole Websocket');
    var_dump($http_client->recv()->data);
});
go(function () {
    // http2
    $http2_client = new Swoole\Coroutine\Http2\Client('localhost', 9501);
    $http2_client->connect();
    $http2_request = new Swoole\Http2\Request;
    $http2_request->method = 'POST';
    $http2_request->data = 'Swoole Http2';
    $http2_client->send($http2_request);
    $http2_response = $http2_client->recv();
    var_dump($http2_response->data);
});
go(function () use ($tcp_options) {
    // tcp
    $tcp_client = new Swoole\Coroutine\Client(SWOOLE_TCP);
    $tcp_client->set($tcp_options);
    $tcp_client->connect('127.0.0.1', 9502);
    $tcp_client->send(tcp_pack('Swoole Tcp'));
    var_dump(tcp_unpack($tcp_client->recv()));
});

Channel

Channel is the only way for exchanging data between coroutines, the development combination of the Coroutine + Channel is the famous CSP programming model.

In Swoole development, Channel is usually used for implementing connection pool or scheduling coroutine concurrent.

The simplest example of a connection pool

In the following example, we have a thousand concurrently requests to redis. Normally, this has exceeded the maximum number of Redis connections setting and will throw a connection exception, but the connection pool based on Channel can perfectly schedule requests. We don't have to worry about connection overload.

class RedisPool
{
    /**@var \Swoole\Coroutine\Channel */
    protected $pool;

    /**
     * RedisPool constructor.
     * @param int $size max connections
     */
    public function __construct(int $size = 100)
    {
        $this->pool = new \Swoole\Coroutine\Channel($size);
        for ($i = 0; $i < $size; $i++) {
            $redis = new \Swoole\Coroutine\Redis();
            $res = $redis->connect('127.0.0.1', 6379);
            if ($res == false) {
                throw new \RuntimeException("failed to connect redis server.");
            } else {
                $this->put($redis);
            }
        }
    }

    public function get(): \Swoole\Coroutine\Redis
    {
        return $this->pool->pop();
    }

    public function put(\Swoole\Coroutine\Redis $redis)
    {
        $this->pool->push($redis);
    }

    public function close(): void
    {
        $this->pool->close();
        $this->pool = null;
    }
}

go(function () {
    $pool = new RedisPool();
    // max concurrency num is more than max connections
    // but it's no problem, channel will help you with scheduling
    for ($c = 0; $c < 1000; $c++) {
        go(function () use ($pool, $c) {
            for ($n = 0; $n < 100; $n++) {
                $redis = $pool->get();
                assert($redis->set("awesome-{$c}-{$n}", 'swoole'));
                assert($redis->get("awesome-{$c}-{$n}") === 'swoole');
                assert($redis->delete("awesome-{$c}-{$n}"));
                $pool->put($redis);
            }
        });
    }
});

Producer and consumers

Some Swoole's clients implement the defer mode for concurrency, but you can still implement it flexible with a combination of coroutines and channels.

go(function () {
    // User: I need you to bring me some information back.
    // Channel: OK! I will be responsible for scheduling.
    $channel = new Swoole\Coroutine\Channel;
    go(function () use ($channel) {
        // Coroutine A: Ok! I will show you the github addr info
        $addr_info = Co::getaddrinfo('github.com');
        $channel->push(['A', json_encode($addr_info, JSON_PRETTY_PRINT)]);
    });
    go(function () use ($channel) {
        // Coroutine B: Ok! I will show you what your code look like
        $mirror = Co::readFile(__FILE__);
        $channel->push(['B', $mirror]);
    });
    go(function () use ($channel) {
        // Coroutine C: Ok! I will show you the date
        $channel->push(['C', date(DATE_W3C)]);
    });
    for ($i = 3; $i--;) {
        list($id, $data) = $channel->pop();
        echo "From {$id}:\n {$data}\n";
    }
    // User: Amazing, I got every information at earliest time!
});

Timer

$id = Swoole\Timer::tick(100, function () {
    echo "⚙️ Do something...\n";
});
Swoole\Timer::after(500, function () use ($id) {
    Swoole\Timer::clear($id);
    echo "⏰ Done\n";
});
Swoole\Timer::after(1000, function () use ($id) {
    if (!Swoole\Timer::exists($id)) {
        echo "✅ All right!\n";
    }
});

The way of coroutine

go(function () {
    $i = 0;
    while (true) {
        Co::sleep(0.1);
        echo "📝 Do something...\n";
        if (++$i === 5) {
            echo "🛎 Done\n";
            break;
        }
    }
    echo "🎉 All right!\n";
});

🔥 Amazing runtime hooks

As of Swoole v4.1.0, we added the ability to transform synchronous PHP network libraries into co-routine libraries using a single line of code.

Simply call the Swoole\Runtime::enableCoroutine() method at the top of your script. In the sample below we connect to php-redis and concurrently read 10k requests in 0.1s:

Swoole\Runtime::enableCoroutine();
$s = microtime(true);
Co\run(function() {
    for ($c = 100; $c--;) {
        go(function () {
            ($redis = new Redis)->connect('127.0.0.1', 6379);
            for ($n = 100; $n--;) {
                assert($redis->get('awesome') === 'swoole');
            }
        });
    }
});
echo 'use ' . (microtime(true) - $s) . ' s';

By calling this method, the Swoole kernel replaces ZendVM stream function pointers. If you use php_stream based extensions, all socket operations can be dynamically converted to be asynchronous IO scheduled by coroutine at runtime!

How many things you can do in 1s?

Sleep 10K times, read, write, check and delete files 10K times, use PDO and MySQLi to communicate with the database 10K times, create a TCP server and multiple clients to communicate with each other 10K times, create a UDP server and multiple clients to communicate with each other 10K times... Everything works well in one process!

Just see what the Swoole brings, just imagine...

Swoole\Runtime::enableCoroutine();
$s = microtime(true);
Co\run(function() {
    // i just want to sleep...
    for ($c = 100; $c--;) {
        go(function () {
            for ($n = 100; $n--;) {
                usleep(1000);
            }
        });
    }

    // 10K file read and write
    for ($c = 100; $c--;) {
        go(function () use ($c) {
            $tmp_filename = "/tmp/test-{$c}.php";
            for ($n = 100; $n--;) {
                $self = file_get_contents(__FILE__);
                file_put_contents($tmp_filename, $self);
                assert(file_get_contents($tmp_filename) === $self);
            }
            unlink($tmp_filename);
        });
    }

    // 10K pdo and mysqli read
    for ($c = 50; $c--;) {
        go(function () {
            $pdo = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', 'root', 'root');
            $statement = $pdo->prepare('SELECT * FROM `user`');
            for ($n = 100; $n--;) {
                $statement->execute();
                assert(count($statement->fetchAll()) > 0);
            }
        });
    }
    for ($c = 50; $c--;) {
        go(function () {
            $mysqli = new Mysqli('127.0.0.1', 'root', 'root', 'test');
            $statement = $mysqli->prepare('SELECT `id` FROM `user`');
            for ($n = 100; $n--;) {
                $statement->bind_result($id);
                $statement->execute();
                $statement->fetch();
                assert($id > 0);
            }
        });
    }

    // php_stream tcp server & client with 12.8K requests in single process
    function tcp_pack(string $data): string
    {
        return pack('n', strlen($data)) . $data;
    }

    function tcp_length(string $head): int
    {
        return unpack('n', $head)[1];
    }

    go(function () {
        $ctx = stream_context_create(['socket' => ['so_reuseaddr' => true, 'backlog' => 128]]);
        $socket = stream_socket_server(
            'tcp://0.0.0.0:9502',
            $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx
        );
        if (!$socket) {
            echo "$errstr ($errno)\n";
        } else {
            $i = 0;
            while ($conn = stream_socket_accept($socket, 1)) {
                stream_set_timeout($conn, 5);
                for ($n = 100; $n--;) {
                    $data = fread($conn, tcp_length(fread($conn, 2)));
                    assert($data === "Hello Swoole Server #{$n}!");
                    fwrite($conn, tcp_pack("Hello Swoole Client #{$n}!"));
                }
                if (++$i === 128) {
                    fclose($socket);
                    break;
                }
            }
        }
    });
    for ($c = 128; $c--;) {
        go(function () {
            $fp = stream_socket_client("tcp://127.0.0.1:9502", $errno, $errstr, 1);
            if (!$fp) {
                echo "$errstr ($errno)\n";
            } else {
                stream_set_timeout($fp, 5);
                for ($n = 100; $n--;) {
                    fwrite($fp, tcp_pack("Hello Swoole Server #{$n}!"));
                    $data = fread($fp, tcp_length(fread($fp, 2)));
                    assert($data === "Hello Swoole Client #{$n}!");
                }
                fclose($fp);
            }
        });
    }

    // udp server & client with 12.8K requests in single process
    go(function () {
        $socket = new Swoole\Coroutine\Socket(AF_INET, SOCK_DGRAM, 0);
        $socket->bind('127.0.0.1', 9503);
        $client_map = [];
        for ($c = 128; $c--;) {
            for ($n = 0; $n < 100; $n++) {
                $recv = $socket->recvfrom($peer);
                $client_uid = "{$peer['address']}:{$peer['port']}";
                $id = $client_map[$client_uid] = ($client_map[$client_uid] ?? -1) + 1;
                assert($recv === "Client: Hello #{$id}!");
                $socket->sendto($peer['address'], $peer['port'], "Server: Hello #{$id}!");
            }
        }
        $socket->close();
    });
    for ($c = 128; $c--;) {
        go(function () {
            $fp = stream_socket_client("udp://127.0.0.1:9503", $errno, $errstr, 1);
            if (!$fp) {
                echo "$errstr ($errno)\n";
            } else {
                for ($n = 0; $n < 100; $n++) {
                    fwrite($fp, "Client: Hello #{$n}!");
                    $recv = fread($fp, 1024);
                    list($address, $port) = explode(':', (stream_socket_get_name($fp, true)));
                    assert($address === '127.0.0.1' && (int)$port === 9503);
                    assert($recv === "Server: Hello #{$n}!");
                }
                fclose($fp);
            }
        });
    }
});
echo 'use ' . (microtime(true) - $s) . ' s';

⌛️ Installation

As with any open source project, Swoole always provides the most reliable stability and the most powerful features in the latest released version. Please ensure as much as possible that you are using the latest version.

Compiling requirements

  • Linux, OS X or Cygwin, WSL
  • PHP 7.2.0 or later (The higher the version, the better the performance.)
  • GCC 4.8 or later

1. Install via PECL (beginners)

pecl install swoole

2. Install from source (recommended)

Please download the source packages from Releases or:

git clone https://github.com/swoole/swoole-src.git && \
cd swoole-src

Compile and install at the source folder:

phpize && \
./configure && \
make && make install

Enable extension in PHP

After compiling and installing to the system successfully, you have to add a new line extension=swoole.so to php.ini to enable Swoole extension.

Extra compiler configurations

for example: ./configure --enable-openssl --enable-sockets

  • --enable-openssl or --with-openssl-dir=DIR
  • --enable-sockets
  • --enable-mysqlnd (need mysqlnd, it just for supporting $mysql->escape method)
  • --enable-swoole-curl

Upgrade

⚠️ If you upgrade from source, don't forget to make clean before you upgrade your swoole

  1. pecl upgrade swoole
  2. cd swoole-src && git pull && make clean && make && sudo make install
  3. if you change your PHP version, please re-run phpize clean && phpize then try to compile

Major change since version 4.3.0

Async clients and API are moved to a separate PHP extension swoole_async since version 4.3.0, install swoole_async:

git clone https://github.com/swoole/ext-async.git
cd ext-async
phpize
./configure
make -j 4
sudo make install

Enable it by adding a new line extension=swoole_async.so to php.ini.

🍭 Benchmark

  • On the open source Techempower Web Framework benchmarks Swoole used MySQL database benchmark to rank first, and all performance tests ranked in the first echelon.
  • You can just run Benchmark Script to quickly test the maximum QPS of Swoole-HTTP-Server on your machine.

🔰️ Security issues

Security issues should be reported privately, via email, to the Swoole develop team [email protected]. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message.

🖊️ Contribution

Your contribution to Swoole development is very welcome!

You may contribute in the following ways:

❤️ Contributors

This project exists thanks to all the people who contribute. [Contributors].

🎙️ Official Evangelist

Demin has been playing with PHP since 2000, focusing on building high-performance, secure web services. He is an occasional conference speaker on PHP and Swoole, and has been working for companies in the states like eBay, Visa and Glu Mobile for years. You may find Demin on Twitter or GitHub.

📃 License

Apache License Version 2.0 see http://www.apache.org/licenses/LICENSE-2.0.html

swoole-src's People

Contributors

artem-from-ua avatar betashepherd avatar bixuehujin avatar deminy avatar devnexen avatar doubaokun avatar dryangkun avatar gxhua avatar huanghantao avatar inokinoki avatar ixqbar avatar kimkit avatar kiss291323003 avatar limingxinleo avatar matyhtf avatar nathanfreeman avatar petk avatar recoye avatar remicollet avatar shenzhe avatar shiguangqi avatar sshymko avatar sy-records avatar taobao-php avatar twose avatar wenxuanguan avatar windrunner414 avatar xyzhu1120 avatar yunnian avatar yurunsoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swoole-src's Issues

出错就退出

发现了一个很致命的问题,就是这个服务,如果在php脚本中出现语法,找不到类等致命错误的时候,服务进程会直接退出,造成服务不可用。
作为服务的话,稳定是必须的。一出错就不提供服务,这肯定不行。请问有没有什么解决方法?
简单说就是虽然出错,但如果不调用错误代码服务不会退出,即使运行错误代码,也能throw 出,但不退出服务进程

Compile failed. "error: ‘EFD_SEMAPHORE’ undeclared (first use in this function)"

/root/test/swoole-swoole-1.6.11-stable/src/pipe/PipeEventfd.c: In function ‘swPipeEventfd_create’:
/root/test/swoole-swoole-1.6.11-stable/src/pipe/PipeEventfd.c:47: error: ‘EFD_SEMAPHORE’ undeclared (first use in this function)
/root/test/swoole-swoole-1.6.11-stable/src/pipe/PipeEventfd.c:47: error: (Each undeclared identifier is reported only once
/root/test/swoole-swoole-1.6.11-stable/src/pipe/PipeEventfd.c:47: error: for each function it appears in.)
make: *** [src/pipe/PipeEventfd.lo] Error 1

Bad archive / package.xml

The swoole-1.6.7.tgz is obviously not created correctly.

  • It contains lot of "build" files which are not needed (*.o, *.lo, ...)
  • It contains files not listed in the package.xml (README.md)
  • It miss files listed in package.xml (README)

Please fix the package.xml and use the "pecl package" command to generate the official archive.

It will be nice to also add the "examples" tree.

Thanks.

在32位环境下swTimer_get_ms()返回溢出

src/core/timer.c
SWINLINE time_t swTimer_get_ms()
{
struct timeval now;
if (gettimeofday(&now, NULL) < 0)
{
swWarn("gettimeofday fail.Error: %s[%d]", strerror(errno), errno);
return SW_ERR;
}
return (now.tv_sec * 1000) + (now.tv_usec / 1000);
}
以上的代码在32位LINUX运行时,会导致time_t溢出,返回负数。

swDataBuffer_clear的逻辑问题

int swDataBuffer_clear(swDataBuffer *data_buffer, int fd)
{
swDataBuffer_item *item = NULL;
swHashMap_add_int(&data_buffer->map, fd, item);
if (item == NULL)
{
swTrace("buffer item not found\n");
return SW_ERR;
}
....
}

在src/network/buffer.c的 swDataBuffer_clear函数,定义一个item=NULL,然后插入到哈希表,但是这个过程item并没有分配内存,也就是item永远都是null,这个会一直返回SW_ERR.

Build PHP extension against shared libswoole

Will be nice to add an option in config.m4 for PHP extension to used shared libswoole instead of bundling it (which is forbidden, in various linux distro, by guidelines).

So, something like :

# the library
cmake .
make
sudo make install
# the php extension
phpize
./configure --with-swoole --with-libswoole ...
make
sudo make install

框架的文档

请问这个框架有文档吗? 介绍上说实现了ORM Log Cache MVC等,但是一个介绍怎么样使用的文档都没有,让人怎么使用啊,不好意思,说的是这个项目 swoole_framework forked from matyhtf/swoole_framework

Webbench Test Swoole Server show WARN and ERROR

Test Code:

$serv = new swoole_server("127.0.0.1", 9501);
$serv->set(array(
    'worker_num' => 8,
 ));
$serv->on('connect', function ($serv, $fd){
    echo "Client:Connect.\n";
});
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
    $serv->send($fd, 'Swoole: '.$data);
    $serv->close($fd);
});
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});
$serv->start();

Webbench Test:

$ webbench -c 100 -t 10 "http://192.168.0.15:9501/"

Command line show:

...
Client:Connect.
Client:Connect.
Client: Close.
Client: Close.
Client: Close.
Client: Close.
[2014-01-21 09:45:44]   WARN    swServer_poll_onReceive_no_buffer: Read from socket[34] fail. Error: Bad file descriptor [9]
Client: Close.
Client:Connect.
[2014-01-21 09:45:44]   WARN    swServer_poll_onReceive_no_buffer: Read from socket[34] fail. Error: Bad file descriptor [9]
Client: Close.
Client: Close.
[2014-01-21 09:45:44]   WARN    swReactorEpoll_wait: [Reactor#0] epoll handle fail. fd=34|type=0
[2014-01-21 09:45:44]   WARN    swServer_poll_onReceive_no_buffer: Read from socket[26] fail. Error: Bad file descriptor [9]
[2014-01-21 09:45:44]   WARN    swReactorEpoll_wait: [Reactor#0] epoll handle fail. fd=26|type=0
Client: Close.
Client: Close.
[2014-01-21 09:45:44]   WARN    swServer_poll_onReceive_no_buffer: Read from socket[40] fail. Error: Bad file descriptor [9]
[2014-01-21 09:45:44]   WARN    swReactorEpoll_wait: [Reactor#0] epoll handle fail. fd=40|type=0
Client: Close.
Client: Close.
Client: Close.
Client: Close.
Client: Close.
Client: Close.
Client: Close.
Client: Close.
[2014-01-21 09:45:44]   WARN    swReactorEpoll_wait: [Reactor#0] epoll handle fail. fd=40|type=0
Client: Close.
[2014-01-21 09:45:44]   WARN    swReactorEpoll_del: epoll remove fd[=48] fail. Error: Bad file descriptor[9]
[2014-01-21 09:45:44]   WARN    swReactorEpoll_del: epoll remove fd[=56] fail. Error: Bad file descriptor[9]
Client: Close.
[2014-01-21 09:45:44]   WARN    swReactorEpoll_del: epoll remove fd[=56] fail. Error: Bad file descriptor[9]
[2014-01-21 09:45:44]   WARN    swServer_poll_onReceive_no_buffer: Read from socket[29] fail. Error: Bad file descriptor [9]
[2014-01-21 09:45:44]   WARN    swReactorEpoll_wait: [Reactor#1] epoll handle fail. fd=29|type=0
Client: Close.
...

Use ZPHP framework Swoole Server
Show php Warning:

Get data {"a":"message\/message","m":"send","fd":"28","content":"123"} from 36 [ip:127.0.0.1:45769]
Get data {"a":"message\/message","m":"send","fd":"28","content":"123"} from 33 [ip:127.0.0.1:45771]
Client 36:close
Client 30:close

Warning: SwooleServer: onClose handler error in /opt/wwwroot/ZPHP/Socket/Adapter/Swoole.php on line 65

Call Stack:
    0.0005     630272   1. {main}() /opt/wwwroot/socket/webroot/main.php:0
    0.0016     693224   2. ZPHP\ZPHP::run() /opt/wwwroot/socket/webroot/main.php:7
    0.0071     789664   3. ZPHP\Server\Adapter\Socket->run() /opt/wwwroot/ZPHP/ZPHP.php:126
    0.0322    1026560   4. ZPHP\Socket\Adapter\Swoole->run() /opt/wwwroot/ZPHP/Server/Adapter/Socket.php:24
    0.0330    1032304   5. swoole_server_start() /opt/wwwroot/ZPHP/Socket/Adapter/Swoole.php:65

Client 30:[ip:127.0.0.1:45773] Connect
Get data {"a":"message\/message","m":"send","fd":"28","content":"123"} from 30 [ip:127.0.0.1:45773]

Warning: SwooleServer: onConnect handler error in /opt/wwwroot/ZPHP/Socket/Adapter/Swoole.php on line 65

Call Stack:
    0.0005     630272   1. {main}() /opt/wwwroot/socket/webroot/main.php:0
    0.0016     693224   2. ZPHP\ZPHP::run() /opt/wwwroot/socket/webroot/main.php:7
    0.0071     789664   3. ZPHP\Server\Adapter\Socket->run() /opt/wwwroot/ZPHP/ZPHP.php:126
    0.0322    1026560   4. ZPHP\Socket\Adapter\Swoole->run() /opt/wwwroot/ZPHP/Server/Adapter/Socket.php:24
    0.0330    1032304   5. swoole_server_start() /opt/wwwroot/ZPHP/Socket/Adapter/Swoole.php:65

Get data {"a":"message\/message","m":"send","fd":"28","content":"123"} from 33 [ip:127.0.0.1:45775]
Client 36:[ip:127.0.0.1:45777] Connect
Get data {"a":"message\/message","m":"send","fd":"28","content":"123"} from 36 [ip:127.0.0.1:45777]
Client 30:close
Client 30:[ip:127.0.0.1:45779] Connect
Get data {"a":"message\/message","m":"send","fd":"28","content":"123"} from 30 [ip:127.0.0.1:45779]

Warning: SwooleServer: onClose handler error in /opt/wwwroot/ZPHP/Socket/Adapter/Swoole.php on line 65

a question

hi, I have read the code and have a question,
the main thread use select and only accept new connections,
and added the new file descriptor to the work threads fd-sets( server.c #117).
is this ok ?
the main & worker are running in different thread, how the worker knows a new fd is added & break from its' sub select/poll function?

I use windows, so I cant build the code. thanks for your reply!

"shutdown" method cannot close manager and worker process

In 1.7.2 version, use the method like "$serv->shutdown();".
It will close master process only, but the manager and worker process still alive.

Here is the terminal output, fyi.
before:
root@john:~# ps aux|grep swoole
root 9005 0.1 0.9 201308 13884 pts/0 Sl+ 16:44 0:00 php-swoole-master-9005
root 9007 0.0 0.2 193112 4304 pts/0 S+ 16:44 0:00 php-swoole-manager
root 9010 0.0 0.3 193428 6096 pts/0 S+ 16:44 0:00 php-swoole-worker-9010
root 9011 0.0 0.3 193428 6096 pts/0 S+ 16:44 0:00 php-swoole-worker-9011
root 9012 0.0 0.4 193372 6180 pts/0 S+ 16:44 0:00 php-swoole-worker-9012
root 9013 0.0 0.4 193372 6180 pts/0 S+ 16:44 0:00 php-swoole-worker-9013

after:
root@john:~# ps aux|grep swoole
root 9007 0.0 0.2 193112 4304 pts/0 S 16:44 0:00 php-swoole-manager
root 9010 0.0 0.4 193428 6444 pts/0 S 16:44 0:00 php-swoole-worker-9010
root 9011 0.0 0.3 193428 6096 pts/0 S 16:44 0:00 php-swoole-worker-9011
root 9012 0.0 0.4 193372 6180 pts/0 S 16:44 0:00 php-swoole-worker-9012
root 9013 0.0 0.4 193372 6180 pts/0 S 16:44 0:00 php-swoole-worker-9013

什么时候出websocket的例子?

这几天在找websocket来在我的php里弄一个聊天功能,但是说php不支持多线程,我就各种找,刚准备用node.js的时候,看到了swoole,看样子可行,希望能出websocket的example让我这菜鸟学习学习

Build warnings

Hi,

New version, lot of new build warnings. :(

I've spent lot of time fixing the previous ones, but it seems you don't care, so I give up.

At least, in 1.6.10

 swoole.c:1103:3: warning: implicit declaration of function 'zend_exception_error' [-Wimplicit-function-declaration]

Such issue (here probably a missing header) could raise awfull runtime issue.

Please consider using -Wall in your dev env.
You can ever add, in config.m4 (keeping system value)

  CFLAGS="$CFLAGS -Wall"

compile error in ver 1.6.12-beta

cc -I. -I/Users/rek/git/github/swoole -DPHP_ATOM_INC -I/Users/rek/git/github/swoole/include -I/Users/rek/git/github/swoole/main -I/Users/rek/git/github/swoole -I/usr/include/php -I/usr/include/php/main -I/usr/include/php/TSRM -I/usr/include/php/Zend -I/usr/include/php/ext -I/usr/include/php/ext/date/lib -I/include -I/Users/rek/git/github/swoole/include -DHAVE_CONFIG_H -Wall -g -O2 -std=gnu89 -c /Users/rek/git/github/swoole/src/os/sendfile.c  -fno-common -DPIC -o src/os/.libs/sendfile.o
/Users/rek/git/github/swoole/src/os/sendfile.c:29:63: error: too many arguments
      to function call, expected 6, have 7
        ret = sendfile(in_fd, out_fd, *offset, size, 0, &sent_bytes, 0);
              ~~~~~~~~                                               ^
/usr/include/sys/socket.h:580:1: note: 'sendfile' declared here
int     sendfile(int, int, off_t, off_t *, struct sf_hdtr *, int);
^
1 error generated.

关于字符串中的'\0'字符

你好,
请问在传输的字符串中插入'\0'字符或者或者其他特殊字符可以吗
我在测试时发现如果传输的字符串中包含'\0'字符就会被截断,后面的内容就不会传输了
比如发送的是:"abcdef\00ABCDEF"
接收到的就只有:"abcdef"
但是利用strlen计算,发送端的长度为13,接收端得到的长度为6
不知道是我的编译环境的问题还是php语言本身的设定就是这样,本人刚学php,好多东西都不懂~

PHP 5.5 broken build

The --enable-async-mysql don't work with PHP 5.5 (ok with 5.4)

 /dev/shm/BUILD/php-pecl-swoole-1.6.7/NTS/swoole.c:376:58: error: 'MYSQLND_NET' has no member named 'stream'

mkostemp is not available everywhere

On RHEL-5

During build:

 /builddir/build/BUILD/php-pecl-swoole-1.7.2/ZTS/src/network/TaskWorker.c:46: warning: implicit declaration of function 'mkostemp'

On PHP startup:

 PHP Warning:  PHP Startup: Unable to load dynamic library 'modules/swoole.so' - modules/swoole.so: undefined symbol: mkostemp in Unknown on line 0

编译出错

/usr/local/service/source/php_swoole/swoole.c: 在函数‘zif_swoole_server_create’中:
/usr/local/service/source/php_swoole/swoole.c:205: 错误:expected expression before ‘;’ token
make: *** [swoole.lo] 错误 1

make create symbol link failed in vagrant

CMake Error: cmake_symlink_library: System Error: Protocol error
make[2]: *** [lib/libswoole.so.1.6.12] Error 1
make[1]: *** [CMakeFiles/swoole_shared.dir/all] Error 2
make: *** [all] Error 2

what's wrong with the make?

CentOS 6.5 x64 PHP 5.4.28 运行异步MYSQLI例子报错.

使用 swoole 1.7.1-stable 版本.
gdb core result:
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-60.el6_4.1)
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
http://www.gnu.org/software/gdb/bugs/...
Reading symbols from /usr/bin/php...(no debugging symbols found)...done.
[New Thread 21318]
Reading symbols from /lib64/libcrypt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libcrypt.so.1
Reading symbols from /usr/lib64/libedit.so.0...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libedit.so.0
Reading symbols from /lib64/libncurses.so.5...(no debugging symbols found)...done.
Loaded symbols for /lib64/libncurses.so.5
Reading symbols from /usr/lib64/libstdc++.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libstdc++.so.6
Reading symbols from /lib64/libz.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libz.so.1
Reading symbols from /lib64/librt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/librt.so.1
Reading symbols from /lib64/libm.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib64/libm.so.6
Reading symbols from /lib64/libdl.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/libdl.so.2
Reading symbols from /lib64/libnsl.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libnsl.so.1
Reading symbols from /usr/lib64/libxml2.so.2...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libxml2.so.2
Reading symbols from /lib64/libgssapi_krb5.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/libgssapi_krb5.so.2
Reading symbols from /lib64/libkrb5.so.3...(no debugging symbols found)...done.
Loaded symbols for /lib64/libkrb5.so.3
Reading symbols from /lib64/libk5crypto.so.3...(no debugging symbols found)...done.
Loaded symbols for /lib64/libk5crypto.so.3
Reading symbols from /lib64/libcom_err.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/libcom_err.so.2
Reading symbols from /usr/lib64/libssl.so.10...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libssl.so.10
Reading symbols from /usr/lib64/libcrypto.so.10...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libcrypto.so.10
Reading symbols from /lib64/libc.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib64/libc.so.6
Reading symbols from /lib64/libresolv.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/libresolv.so.2
Reading symbols from /lib64/libfreebl3.so...(no debugging symbols found)...done.
Loaded symbols for /lib64/libfreebl3.so
Reading symbols from /lib64/libtinfo.so.5...(no debugging symbols found)...done.
Loaded symbols for /lib64/libtinfo.so.5
Reading symbols from /lib64/ld-linux-x86-64.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/ld-linux-x86-64.so.2
Reading symbols from /lib64/libgcc_s.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libgcc_s.so.1
Reading symbols from /lib64/libpthread.so.0...(no debugging symbols found)...done.
[Thread debugging using libthread_db enabled]
Loaded symbols for /lib64/libpthread.so.0
Reading symbols from /lib64/libkrb5support.so.0...(no debugging symbols found)...done.
Loaded symbols for /lib64/libkrb5support.so.0
Reading symbols from /lib64/libkeyutils.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libkeyutils.so.1
Reading symbols from /lib64/libselinux.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libselinux.so.1
Reading symbols from /usr/lib64/php/modules/apc.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/apc.so
Reading symbols from /usr/lib64/php/modules/bcmath.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/bcmath.so
Reading symbols from /usr/lib64/php/modules/bz2.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/bz2.so
Reading symbols from /lib64/libbz2.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libbz2.so.1
Reading symbols from /usr/lib64/php/modules/calendar.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/calendar.so
Reading symbols from /usr/lib64/php/modules/ctype.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/ctype.so
Reading symbols from /usr/lib64/php/modules/curl.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/curl.so
Reading symbols from /usr/lib64/libcurl.so.4...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libcurl.so.4
Reading symbols from /lib64/libidn.so.11...(no debugging symbols found)...done.
Loaded symbols for /lib64/libidn.so.11
Reading symbols from /lib64/libldap-2.4.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/libldap-2.4.so.2
Reading symbols from /usr/lib64/libssl3.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libssl3.so
Reading symbols from /usr/lib64/libsmime3.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libsmime3.so
Reading symbols from /usr/lib64/libnss3.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libnss3.so
Reading symbols from /usr/lib64/libnssutil3.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libnssutil3.so
Reading symbols from /lib64/libplds4.so...(no debugging symbols found)...done.
Loaded symbols for /lib64/libplds4.so
Reading symbols from /lib64/libplc4.so...(no debugging symbols found)...done.
Loaded symbols for /lib64/libplc4.so
Reading symbols from /lib64/libnspr4.so...(no debugging symbols found)...done.
Loaded symbols for /lib64/libnspr4.so
Reading symbols from /usr/lib64/libssh2.so.1...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libssh2.so.1
Reading symbols from /lib64/liblber-2.4.so.2...(no debugging symbols found)...done.
Loaded symbols for /lib64/liblber-2.4.so.2
Reading symbols from /usr/lib64/libsasl2.so.2...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libsasl2.so.2
Reading symbols from /usr/lib64/php/modules/exif.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/exif.so
Reading symbols from /usr/lib64/php/modules/fileinfo.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/fileinfo.so
Reading symbols from /usr/lib64/php/modules/ftp.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/ftp.so
Reading symbols from /usr/lib64/php/modules/gd.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/gd.so
Reading symbols from /usr/lib64/libt1.so.5...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libt1.so.5
Reading symbols from /usr/lib64/libX11.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libX11.so.6
Reading symbols from /usr/lib64/libXpm.so.4...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libXpm.so.4
Reading symbols from /usr/lib64/libpng12.so.0...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libpng12.so.0
Reading symbols from /usr/lib64/libjpeg.so.62...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libjpeg.so.62
Reading symbols from /usr/lib64/libfreetype.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libfreetype.so.6
Reading symbols from /usr/lib64/libxcb.so.1...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libxcb.so.1
Reading symbols from /usr/lib64/libXau.so.6...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libXau.so.6
Reading symbols from /usr/lib64/php/modules/gettext.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/gettext.so
Reading symbols from /usr/lib64/php/modules/gmp.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/gmp.so
Reading symbols from /usr/lib64/libgmp.so.3...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libgmp.so.3
Reading symbols from /usr/lib64/php/modules/iconv.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/iconv.so
Reading symbols from /usr/lib64/php/modules/json.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/json.so
Reading symbols from /usr/lib64/php/modules/mbstring.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/mbstring.so
Reading symbols from /usr/lib64/php/modules/mcrypt.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/mcrypt.so
Reading symbols from /usr/lib64/libmcrypt.so.4...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libmcrypt.so.4
Reading symbols from /usr/lib64/libltdl.so.7...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libltdl.so.7
Reading symbols from /usr/lib64/php/modules/mysqlnd.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/mysqlnd.so
Reading symbols from /usr/lib64/php/modules/mysqlnd_mysql.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/mysqlnd_mysql.so
Reading symbols from /usr/lib64/php/modules/mysqlnd_mysqli.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/mysqlnd_mysqli.so
Reading symbols from /usr/lib64/php/modules/pdo.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/pdo.so
Reading symbols from /usr/lib64/php/modules/pdo_mysqlnd.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/pdo_mysqlnd.so
Reading symbols from /usr/lib64/php/modules/pdo_sqlite.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/pdo_sqlite.so
Reading symbols from /usr/lib64/libsqlite3.so.0...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/libsqlite3.so.0
Reading symbols from /usr/lib64/php/modules/phar.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/phar.so
Reading symbols from /usr/lib64/php/modules/posix.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/posix.so
Reading symbols from /usr/lib64/php/modules/redis.so...done.
Loaded symbols for /usr/lib64/php/modules/redis.so
Reading symbols from /usr/lib64/php/modules/shmop.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/shmop.so
Reading symbols from /usr/lib64/php/modules/simplexml.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/simplexml.so
Reading symbols from /usr/lib64/php/modules/sockets.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/sockets.so
Reading symbols from /usr/lib64/php/modules/swoole.so...done.
Loaded symbols for /usr/lib64/php/modules/swoole.so
Reading symbols from /usr/lib64/php/modules/httpparser.so...done.
Loaded symbols for /usr/lib64/php/modules/httpparser.so
Reading symbols from /usr/lib64/php/modules/sqlite3.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/sqlite3.so
Reading symbols from /usr/lib64/php/modules/sysvmsg.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/sysvmsg.so
Reading symbols from /usr/lib64/php/modules/sysvsem.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/sysvsem.so
Reading symbols from /usr/lib64/php/modules/sysvshm.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/sysvshm.so
Reading symbols from /usr/lib64/php/modules/tokenizer.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/tokenizer.so
Reading symbols from /usr/lib64/php/modules/uuid.so...done.
Loaded symbols for /usr/lib64/php/modules/uuid.so
Reading symbols from /lib64/libuuid.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib64/libuuid.so.1
Reading symbols from /usr/lib64/php/modules/xml.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/xml.so
Reading symbols from /usr/lib64/php/modules/zip.so...(no debugging symbols found)...done.
Loaded symbols for /usr/lib64/php/modules/zip.so
Core was generated by `php -c etc/php.ini async_mysql.php'.
Program terminated with signal 11, Segmentation fault.
#0 0x00007fa825d378e9 in zif_swoole_event_add (ht=, return_value=0x7fa830d16df0,

return_value_ptr=<value optimized out>, this_ptr=<value optimized out>,
return_value_used=<value optimized out>) at /opt/swoole-swoole-1.7.1-stable/swoole_client.c:800

800 if (!ZVAL_IS_NULL(cb_write))
Missing separate debuginfos, use: debuginfo-install php54w-cli-5.4.28-1.w6.x86_64
(gdb) bt
#0 0x00007fa825d378e9 in zif_swoole_event_add (ht=, return_value=0x7fa830d16df0,

return_value_ptr=<value optimized out>, this_ptr=<value optimized out>,
return_value_used=<value optimized out>) at /opt/swoole-swoole-1.7.1-stable/swoole_client.c:800

#1 0x00000000005a4159 in dtrace_execute_internal ()
#2 0x000000000062e955 in ?? ()
#3 0x000000000061c4d8 in execute ()
#4 0x00000000005a427e in dtrace_execute ()
#5 0x00000000005b1f70 in zend_execute_scripts ()
#6 0x0000000000554958 in php_execute_script ()
#7 0x000000000065de53 in ?? ()
#8 0x000000000065e618 in ?? ()
#9 0x000000366ca1ed1d in __libc_start_main () from /lib64/libc.so.6
#10 0x0000000000421009 in _start ()

(gdb) f 1
#1 0x00000000005a4159 in dtrace_execute_internal ()

(gdb) f 0
#0 0x00007fa825d378e9 in zif_swoole_event_add (ht=, return_value=0x7fa830d16df0,

return_value_ptr=<value optimized out>, this_ptr=<value optimized out>,
return_value_used=<value optimized out>) at /opt/swoole-swoole-1.7.1-stable/swoole_client.c:800

800 if (!ZVAL_IS_NULL(cb_write))

编译时参数 --enable-swoole-debug --enable-msgqueue --enable-async-mysql --with-swoole

编译报错 ld: library not found for -lrt

configuration完毕,make出错
机器环境:

  • php5.5.1
  • macos x 10.8.4
  • clang:
➜  swoole-swoole-1.5.5  clang -v
Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix

错误信息:

/bin/sh /Users/robbin/Downloads/swoole-swoole-1.5.5/libtool --mode=link cc -DPHP_ATOM_INC -I/Users/robbin/Downloads/swoole-swoole-1.5.5/include -I/Users/robbin/Downloads/swoole-swoole-1.5.5/main -I/Users/robbin/Downloads/swoole-swoole-1.5.5 -I/Users/robbin/.phpenv/versions/5.5.1/include/php -I/Users/robbin/.phpenv/versions/5.5.1/include/php/main -I/Users/robbin/.phpenv/versions/5.5.1/include/php/TSRM -I/Users/robbin/.phpenv/versions/5.5.1/include/php/Zend -I/Users/robbin/.phpenv/versions/5.5.1/include/php/ext -I/Users/robbin/.phpenv/versions/5.5.1/include/php/ext/date/lib -I/include  -DHAVE_CONFIG_H  -g -O2   -o swoole.la -export-dynamic -avoid-version -prefer-pic -module -rpath /Users/robbin/Downloads/swoole-swoole-1.5.5/modules  swoole.lo src/core/Base.lo src/core/RingQueue.lo src/core/Chan.lo src/memory/ShareMemory.lo src/memory/MemPool.lo src/factory/Factory.lo src/factory/FactoryThread.lo src/factory/FactoryProcess.lo src/reactor/ReactorBase.lo src/reactor/ReactorSelect.lo src/reactor/ReactorPoll.lo src/reactor/ReactorEpoll.lo src/reactor/ReactorKqueue.lo src/pipe/PipeBase.lo src/pipe/PipeEventfd.lo src/pipe/PipeUnsock.lo src/pipe/PipeMsg.lo src/lock/Semaphore.lo src/lock/Mutex.lo src/lock/RWLock.lo src/lock/FileLock.lo src/network/Server.lo src/network/Client.lo src/network/buffer.lo -lrt
cc ${wl}-flat_namespace ${wl}-undefined ${wl}suppress -o .libs/swoole.so -bundle  .libs/swoole.o src/core/.libs/Base.o src/core/.libs/RingQueue.o src/core/.libs/Chan.o src/memory/.libs/ShareMemory.o src/memory/.libs/MemPool.o src/factory/.libs/Factory.o src/factory/.libs/FactoryThread.o src/factory/.libs/FactoryProcess.o src/reactor/.libs/ReactorBase.o src/reactor/.libs/ReactorSelect.o src/reactor/.libs/ReactorPoll.o src/reactor/.libs/ReactorEpoll.o src/reactor/.libs/ReactorKqueue.o src/pipe/.libs/PipeBase.o src/pipe/.libs/PipeEventfd.o src/pipe/.libs/PipeUnsock.o src/pipe/.libs/PipeMsg.o src/lock/.libs/Semaphore.o src/lock/.libs/Mutex.o src/lock/.libs/RWLock.o src/lock/.libs/FileLock.o src/network/.libs/Server.o src/network/.libs/Client.o src/network/.libs/buffer.o  -lrt
ld: library not found for -lrt
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [swoole.la] Error 1

exapmle\server.php中的finish函数有问题.

exapmle\server.php中的finish函数有问题.

function my_onFinish(swoole_server $serv, $data)

应该是三个参数,少了个task_id

function my_onFinish(swoole_server $serv, $task_id, $data)

能否给一个爬虫的例子

hi, 能否给一个爬虫的例子,比如一个请求触发查询另个一个外部服务,返回这个外部服务返回的数据。

SW_BUFFER_SIZE=8192

server.php

function my_onReceive($serv, $fd, $from_id, $data)
{
    //echo "Client:Data. fd=$fd|from_id=$from_id|data=$data\n";
    swoole_server_send($serv, $fd, $data);
    //echo "len=".strlen($data)."\n & data=\n$data\n";
}

client.php

<?php
$clients = array();
for($i = 0; $i < 1; $i++){
    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); //同步阻塞
    $ret = $client->connect('127.0.0.1', 9501, 0.5, 0);
    if(!$ret)
    {
        echo "Over flow. errno=".$client->errCode;
        die("\n");
    }
    $clients[] = $client;
}
sleep(1);
while (1) {
    foreach ($clients as $client) {
        $buf = "";
        for ($i = 0; $i < 8192; $i++) {
            $buf .= chr(rand(0, 255));
        }
        echo "before len=" . strlen($buf) . "\n";
        $client->send($buf);
        $data = $client->recv(8192, 0);
        echo "after len=" . strlen($data) . "\n";
        if (strcmp($buf, $data) != 0) {
            die("mismatch");
        }
    }
    sleep(1);
}

client端结果($client->recv(8192, 1)也是同样的结果):

before len=8192
after len=0
mismatch

Should use php_error_docref not zend_error

Antony Dovgal:
You really shouldn't be using zend_error().
Take a look at PHP sources, zend_error() is used only in Zend Engine itself for true engineerrors, all PHP extensions use php_error_docref() instead, which allows to call custom error handlers, do the logging and other stuff.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.