Swoole主要功能: PHP语言的异步、并行、高性能网络通信框架,使用纯C语言编写,提供了PHP语言的异步多线程服务器,异步TCP/UDP网络客户端,异步MySQL,数据库连接池,AsyncTask,消息队列,毫秒定时器,异步文件读写,异步DNS查询。
WebSocket Server
$serv = new swoole_websocket_server("127.0.0.1", 9502);$serv->on('Open', function($server, $req) { echo "connection open: ".$req->fd;});$serv->on('Message', function($server, $frame) { echo "message: ".$frame->data; $server->push($frame->fd, json_encode(["hello", "world"]));});$serv->on('Close', function($server, $fd) { echo "connection close: ".$fd;});$serv->start();
TCP 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();
TCP 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){ 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);
自己工作中用到的就这三个,具体的配置和更多的功能,可以访问swoole网站:
注明: Apache 配置swoole的时候,记得在两个配置文件php.ini 中,加入 swoole.so 否则会导致部分访问无效