PHP使用swoole編寫簡單的echo伺服器示例
阿新 • • 發佈:2020-03-12
本文例項講述了PHP使用swoole編寫簡單的echo伺服器。分享給大家供大家參考,具體如下:
server.php程式碼如下:
<?php class EchoServer { protected $serv = null; public function __construct() { $this->serv = new swoole_server('0.0.0.0',8888); //配置引數 $this->serv->set(array( 'worker_num' => 4,'daemonize' => 0,)); //註冊回撥函式 $this->serv->on('start',array($this,'start')); $this->serv->on('connect','connect')); $this->serv->on('receive','receive')); $this->serv->on('close','close')); //啟動服務 $this->serv->start(); } public function start($serv) { echo "start \n"; } //有客戶端連線時 public function connect($serv,$fd) { echo "connect \n"; $serv->send($fd,"hello \n"); } public function close($serv,$fd) { echo "close \n"; } public function receive($serv,$fd,$from_id,$data) { echo "get message {$fd} : {$data} \n"; //向客戶端傳送資訊 $serv->send($fd,$data . "\n"); } } $serv = new EchoServer();
client.php程式碼如下:
<?php class EchoClient { protected $client = null; public function __construct() { //注意這裡需設定為非同步,不然下面無法設定事件回撥函式 $this->client = new swoole_client(SWOOLE_SOCK_TCP,SWOOLE_SOCK_ASYNC); $this->client->on('connect','connect')); $this->client->on('receive','receive')); $this->client->on('close','close')); $this->client->on('error','error')); //連線服務端 $this->client->connect('0.0.0.0',8888); } public function connect($client) { echo "connect \n"; } public function receive($client,$data) { echo "server send: {$data}"; //向標準輸出寫入資料 fwrite(STDOUT,"請輸入訊息:"); //獲取標準輸入資料 $msg = trim(fgets(STDIN)); //向服務端傳送資料 $client->send($msg); } public function close($client) { echo "close \n"; } public function error($client) { echo "error \n"; } } $cli = new EchoClient();
然後分別執行這兩個指令碼
> /data/php56/bin/php server.php > /data/php56/bin/php client.php
執行結果如下:
更多關於PHP相關內容感興趣的讀者可檢視本站專題:《PHP網路程式設計技巧總結》、《php socket用法總結》、《php面向物件程式設計入門教程》、《PHP資料結構與演算法教程》及《php程式設計演算法總結》
希望本文所述對大家PHP程式設計有所幫助。