PHP使用swoole編寫簡單的echo服務器示例
本文實例講述了PHP使用swoole編寫簡單的echo服務器。分享給大家供大家參考,具體如下:
server.php代碼如下:
<?phpclass EchoServer { protected $serv = null; public function __construct() { $this->serv = new swoole_server(’0.0.0.0’, 8888); //配置參數(shù) $this->serv->set(array( ’worker_num’ => 4, ’daemonize’ => 0, )); //注冊回調(diào)函數(shù) $this->serv->on(’start’, array($this, ’start’)); $this->serv->on(’connect’, array($this, ’connect’)); $this->serv->on(’receive’, array($this, ’receive’)); $this->serv->on(’close’, array($this, ’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'; //向客戶端發(fā)送信息 $serv->send($fd, $data . 'n'); }} $serv = new EchoServer();
client.php代碼如下:
<?phpclass EchoClient { protected $client = null; public function __construct() { //注意這里需設置為異步,不然下面無法設置事件回調(diào)函數(shù) $this->client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); $this->client->on(’connect’, array($this, ’connect’)); $this->client->on(’receive’, array($this, ’receive’)); $this->client->on(’close’, array($this, ’close’)); $this->client->on(’error’, array($this, ’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}'; //向標準輸出寫入數(shù)據(jù) fwrite(STDOUT, '請輸入消息:'); //獲取標準輸入數(shù)據(jù) $msg = trim(fgets(STDIN)); //向服務端發(fā)送數(shù)據(jù) $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
運行結(jié)果如下:
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP網(wǎng)絡編程技巧總結(jié)》、《php socket用法總結(jié)》、《php面向?qū)ο蟪绦蛟O計入門教程》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》及《php程序設計算法總結(jié)》
希望本文所述對大家PHP程序設計有所幫助。
相關(guān)文章:
1. asp讀取xml文件和記數(shù)2. IDEA中 Getter、Setter 注解不起作用的問題如何解決3. Android CountDownTimer案例總結(jié)4. 簡體中文轉(zhuǎn)換為繁體中文的PHP函數(shù)5. Python 中如何使用 virtualenv 管理虛擬環(huán)境6. 多個SpringBoot項目采用redis實現(xiàn)Session共享功能7. python利用opencv實現(xiàn)顏色檢測8. CSS自定義滾動條樣式案例詳解9. 每日六道java新手入門面試題,通往自由的道路第二天10. PHP實現(xiàn)基本留言板功能原理與步驟詳解
