国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

PHP使用swoole編寫簡單的echo服務器示例

瀏覽:154日期:2022-09-11 10:03:07

本文實例講述了PHP使用swoole編寫簡單的echo服務器。分享給大家供大家參考,具體如下:

server.php代碼如下:

<?phpclass 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’, 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'; //向客戶端發送信息 $serv->send($fd, $data . 'n'); }} $serv = new EchoServer();

client.php代碼如下:

<?phpclass EchoClient { protected $client = null; public function __construct() { //注意這里需設置為異步,不然下面無法設置事件回調函數 $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}'; //向標準輸出寫入數據 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使用swoole編寫簡單的echo服務器示例

PHP使用swoole編寫簡單的echo服務器示例

更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP網絡編程技巧總結》、《php socket用法總結》、《php面向對象程序設計入門教程》、《PHP數據結構與算法教程》及《php程序設計算法總結》

希望本文所述對大家PHP程序設計有所幫助。

標簽: PHP
相關文章:
主站蜘蛛池模板: 富民县| 阿尔山市| 临猗县| 弋阳县| 石柱| 咸阳市| 仪陇县| 渑池县| 德保县| 连江县| 兰考县| 庐江县| 那坡县| 府谷县| 独山县| 凯里市| 巴彦淖尔市| 石景山区| 莱芜市| 万载县| 崇明县| 宜春市| 交口县| 饶阳县| 姚安县| 龙岩市| 连南| 资中县| 林州市| 彰化县| 灌阳县| 疏附县| 梅河口市| 青州市| 株洲市| 乡城县| 无棣县| 枣庄市| 津南区| 都昌县| 通化县|