官方定義:
PHP的異步、並行、高性能網絡通信引擎,使用純C語言編寫,提供了PHP語言的異步多線程服務器,異步TCP/UDP網絡客戶端,異步MySQL,異步Redis,數據庫連接池,AsyncTask,消息隊列,毫秒定時器,異步文件讀寫,異步DNS查詢。 Swoole內置了Http/WebSocket服務器端/客戶端、Http2.0服務器端。
Swoole可以廣泛應用於互聯網、移動通信、企業軟件、雲計算、網絡游戲、物聯網、車聯網、智能家居等領域。 使用PHP+Swoole作為網絡通信框架,可以使企業IT研發團隊的效率大大提升,更加專注於開發創新產品。
swoole 擴展安裝及案例來源:http://wiki.swoole.com/wiki/page/6.html
簡單案例:
<?php class Server { private $serv; public function __construct() { $this->serv = new swoole_server("0.0.0.0", 9501); $this->serv->set(array( 'worker_num' => 8, 'daemonize' => false, 'max_request' => 10000, 'dispatch_mode' => 2, 'debug_mode' => 1 )); $this->serv->on('Start', array($this, 'onStart')); $this->serv->on('Connect', array($this, 'onConnect')); $this->serv->on('Receive', array($this, 'onReceive')); $this->serv->on('Close', array($this, 'onClose')); $this->serv->start(); } public function onStart($serv) { echo "Start\n"; } public function onConnect($serv, $fd, $from_id) { $serv->send($fd, "Hello {$fd}!"); } public function onReceive(swoole_server $serv, $fd, $from_id, $data) { echo "Get Message From Client {$fd}:{$data}\n"; } public function onClose($serv, $fd, $from_id) { echo "Client {$fd} close connection\n"; } } // 啟動服務器 $server = new Server();
<?php class Client { private $client; public function __construct() { $this->client = new swoole_client(SWOOLE_SOCK_TCP); } public function connect() { if (!$this->client->connect("127.0.0.1", 9501, 1)) { echo "Error: {$fp->errMsg}[{$fp->errCode}]\n"; } $message = $this->client->recv(); echo "Get Message From Server:{$message}\n"; fwrite(STDOUT, "請輸入消息:"); $msg = trim(fgets(STDIN)); $this->client->send($msg); } } $client = new Client(); $client->connect();
分別打開兩個終端輸入:php server.php php client.php 即可看到效果!