Swoole开发PHP的高性能高并发TCP/UDP Server

Swoole的网络IO部分基于多线程的epoll/kqueue事件循环,是全异步非阻塞的。 业务逻辑部分既可以像node.js一样全异步回调执行,也可以多进程同步阻塞方式来运行。这样既保证了Server能够应对高并发和大量TCP连接。又保证业务代码仍然可以简单的编写。
优势
纯C编写无依赖
并发10万TCP连接
TCP+UDP同时支持
Server+Client
网络异步/业务
同步支持多进程/多线程
CPU亲和性/守护进程
简单开发效率高

 

Server

$serv = new swoole_server("127.0.0.1", 9501);
$serv->set(array(
    'worker_num' => 8,
    'daemonize' => true, //是否作为守护进程
));
$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();

Client

$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 = ""){
    //$data = $cli->recv(); //低于swoole1.6.10需要调用
    echo "Receive: ".$data.PHP_EOL;
});
$client->on("error", function($cli){
    echo "connect fail\n";
});
$client->on("close", function($cli){
    echo "connection close\n";
    //$cli->close(); //低于swoole1.6.10需要调用
});
$client->connect('127.0.0.1', 9501, 0.5);

Event

$fp = stream_socket_client("tcp://127.0.0.1:80", $code, $msg, 3);
if (!$fp) {
    exit("$errstr ($errno)\n");
}
$http_request = "GET /index.html HTTP/1.1\r\n";
$http_request .= "Host: localhost\r\n\r\n";
fwrite($fp, $http_request);
swoole_event_add($fp, function($fp){
    echo fread($fp, 8192);
    swoole_event_del($fp);
    fclose($fp);
});
echo "http response:\n";
//swoole_event_wait(); //低于PHP5.4需要加swoole_event_wait

Task

$serv = new swoole_server("127.0.0.1", 9502);
$serv->set(array('task_worker_num' => 4));
$serv->on('Receive', function($serv, $fd, $from_id, $data) {
    $task_id = $serv->task("Async");
    echo "Dispath AsyncTask: id=$task_id\n";
});
$serv->on('Task', function ($serv, $task_id, $from_id, $data) {
    echo "New AsyncTask[id=$task_id]".PHP_EOL;
    $serv->finish("$data -> OK");
});
$serv->on('Finish', function ($serv, $task_id, $data) {
    echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});
$serv->start();

Leave a Reply