Swoole is an event-based & concurrent framework for internet applications, written in C, for PHP.
The network layer in Swoole is event-based and takes full advantage of the underlaying epoll/kqueue implementation, making it really easy to serve thousands of connections.
In the request processing part, Swoole uses a multi-process model. Every process works as a worker. All business logic is executed in workers, synchronously.
With the synchronous logic execution, you can easily write large and robust applications and take advantage of almost all libraries available to the PHP community.
Unlike traditional apache/php-fpm stuff, the memory allocated in Swoole will not be free'd after a request, which can improve preformance a lot.
Traditional PHP applications almost always run behind Apache/Nginx, without much control of the request. This brings several limitations:
- All memory is free'd after request. All PHP code needs be re-compiled on every request. Even with opcache enabled, all opcode still needs to be re-executed.
- It is almost impossible to implement long connections and connections pooling techniques.
- Implementing asynchronous tasks requires 3rd party queue servers, such as rabbitmq and beanstalkd.
- Implementing realtime applications such as chatting server requires 3rd party languages, nodejs for example.
This why Swoole appeared. Swoole extends the use cases of PHP, and brings all these possibilities to the PHP world. By using Swoole, you can build enhanced web applications with more control, realtime chatting servers, etc more easily.
- PHP 5.3+
- Linux, OS X and basic Windows support (Thanks to cygwin)
-
Install via pecl
pecl install swoole
-
Install from source
sudo apt-get install php5-dev git clone https://github.com/swoole/swoole-src.git cd swoole-src phpize ./configure make && make install
Swoole includes components for different purposes: Server, Task Worker, Timer, Event and Async IO. With these components, Swoole allows you to build many features.
This is the most important part in Swoole. It provides necessary infrastructure to build server applications. With Swoole server, you can build web servers, chat messaging servers, game servers and almost anything you want.
The following example shows a simple echo server.
// create a server instance
$serv = new swoole_server("127.0.0.1", 9501);
// attach handler for connect event, once client connected to server the registered handler will be executed
$serv->on('connect', function ($serv, $fd){
echo "Client:Connect.\n";
});
// attach handler for receive event, every piece of data received by server, the registered handler will be
// executed. And all custom protocol implementation should be located there.
$serv->on('receive', function ($serv, $fd, $from_id, $data) {
$serv->send($fd, $data);
});
$serv->on('close', function ($serv, $fd) {
echo "Client: Close.\n";
});
// start our server, listen on port and ready to accept connections
$serv->start();
Try to extend your server and implement what you want!
$http = new swoole_http_server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
$ws = new swoole_http_server("0.0.0.0", 9502);
$ws->on('message', function ($frame) {
$frame->message("server send: ".$frame->data);
});
$ws->start();
Swoole brings you two types of workers: server workers and task workers. Server workers are for request handling, as demonstrated above. Task workers are for task execution. With task workers, we can make our task executed asynchronously without blocking the server workers.
Task workers are mainly used for time-consuming tasks, such as sending password recovery emails. And ensure the main request returns as soon as possible.
The following example shows a simple server with task support.
$serv = new swoole_server("127.0.0.1", 9502);
// sets server configuration, we set task_worker_num config greater than 0 to enable task workers support
$serv->set(array('task_worker_num' => 4));
// attach handler for receive event, which have explained above.
$serv->on('receive', function($serv, $fd, $from_id, $data) {
// we dispath a task to task workers by invoke the task() method of $serv
// this method returns a task id as the identity of ths task
$task_id = $serv->task($data);
echo "Dispath AsyncTask: id=$task_id\n";
});
// attach handler for task event, the handler will be executed in task workers.
$serv->on('task', function ($serv, $task_id, $from_id, $data) {
// handle the task, do what you want with $data
echo "New AsyncTask[id=$task_id]".PHP_EOL;
// after the task task is handled, we return the results to caller worker.
$serv->finish("$data -> OK");
});
// attach handler for finish event, the handler will be executed in server workers, the same worker dispatched this task before.
$serv->on('finish', function ($serv, $task_id, $data) {
echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});
$serv->start();
Swoole also supports synchronous tasks. To use synchronous tasks, just simply replace
$serv->task($data)
with $serv->taskwait($data)
. Unlike task()
, taskwait()
will wait for a task to
complete before it returns its response.
Swoole has built in millisecond timer support. By using the timer, it is easy to get a block of code executed periodically (really useful for managing interval tasks).
To demonstrate how the timer works, here is a small example:
$serv->on('timer', function ($interval) {
switch($interval) {
case 10000: // timer1
// code for timer1
break;
case 20000: // timer2
// code for timer2
break;
}
});
$serv->on('workerStart', function ($serv) {
$serv->addtimer(10000);
$serv->addtimer(20000);
//Remove timer1 500 milliseconds after
$serv->after(500, function(){
$serv->deltimer(10000);
});
});
In the example above, we first set the timer
event handler to swoole_server
to enable timer support.
Then, we add two timers by calling bool swoole_server::addtimer($interval)
once the server started.
To handle multiple timers, we switch the $interval
in registered handler and do what we want to do.
Swoole's I/O layer is event-based, which is very convenient to add your own file descriptor to Swoole's main eventloop. With event support, you can also build fully asynchronous applications with Swoole.
To use events in Swoole, we can use swoole_event_set()
to register event handler to sepecified file descriptor,
once registered descriptors become readable or writeable, our registered handler will be invoked. Also, we can
using bool swoole_event_del(int $fd);
to remove registered file descriptor from eventloop.
The following are prototypes for the related functions:
bool swoole_event_add($fd, mixed $read_callback, mixed $write_callback, int $flag);
bool swoole_event_set($fd, mixed $read_callback, mixed $write_callback, int $flag);
bool swoole_event_del($fd);
The $fid
parameter can be one of the following types:
- unix file descriptor
- stream resource created by
stream_socket_client()/fsockopen()
- sockets resources created by
socket_create()
in sockets extension (require compile swoole with --enable-sockets support)
The $read_callback
and $write_callback
are callbacks for corresponding read/write event.
The $flag
is a mask to indicate what type of events we should get notified, can be SWOOLE_EVENT_READ
,
SWOOLE_EVENT_WRITE
or SWOOLE_EVENT_READ | SWOOLE_EVENT_WRITE
Swoole's Async IO provide the ability to read/write file and lookup dns records asynchronously. The following are signatures for these functions:
bool swoole_async_readfile(string $filename, mixed $callback);
bool swoole_async_writefile('test.log', $file_content, mixed $callback);
bool swoole_async_read(string $filename, mixed $callback, int $trunk_size = 8192);
bool swoole_async_write(string $filename, string $content, int $offset = -1, mixed $callback = NULL);
void swoole_async_dns_lookup(string $domain, function($host, $ip){});
bool swoole_timer_add($interval_ms, mixed $callback);
bool swoole_timer_del($interval_ms);
bool swoole_timer_after($after_n_ms, mixed $callback);
Refer API Reference for more detail information of these functions.
Swoole also provides a Client component to build tcp/dup clients in both asynchronous and synchronous ways.
Swoole uses the swoole_client
class to expose all its functionalities.
synchronous blocking:
$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
die("connect failed.");
}
if (!$client->send("hello world"))
{
die("send failed.");
}
$data = $client->recv();
if (!$data)
{
die("recv failed.");
}
$client->close();
asynchronous nonblocking:
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function($cli) {
$cli->send("hello world\n");
});
$client->on("receive", function($cli, $data){
echo "Received: ".$data."\n";
});
$client->on("error", function($cli){
echo "Connect failed\n";
});
$client->on("close", function($cli){
echo "Connection close\n";
});
$client->connect('127.0.0.1', 9501, 0.5);
The following methods are available in swoole_client:
swoole_client::__construct(int $sock_type, int $is_sync = SWOOLE_SOCK_SYNC, string $key);
int swoole_client::on(string $event, mixed $callback);
bool swoole_client::connect(string $host, int $port, float $timeout = 0.1, int $flag = 0)
bool swoole_client::isConnected();
int swoole_client::send(string $data);
bool swoole_client::sendfile(string $filename)
string swoole_client::recv(int $size = 65535, bool $waitall = 0);
bool swoole_client::close();
Refer API Reference for more detail information of these functions.
- SwooleFramework Web framework powered by Swoole
Your contribution to Swoole development is very welcome!
You may contribute in the following ways:
- Repost issues and feedback
- Submit fixes, features via Pull Request
- Write/polish documentation
Apache License Version 2.0 see http://www.apache.org/licenses/LICENSE-2.0.html