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

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

PHP使用swoole編寫(xiě)簡(jiǎn)單的echo服務(wù)器示例

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

本文實(shí)例講述了PHP使用swoole編寫(xiě)簡(jiǎn)單的echo服務(wù)器。分享給大家供大家參考,具體如下:

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, )); //注冊(cè)回調(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’)); //啟動(dòng)服務(wù) $this->serv->start(); } public function start($serv) { echo 'start n'; } //有客戶(hù)端連接時(shí) 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'; //向客戶(hù)端發(fā)送信息 $serv->send($fd, $data . 'n'); }} $serv = new EchoServer();

client.php代碼如下:

<?phpclass EchoClient { protected $client = null; public function __construct() { //注意這里需設(shè)置為異步,不然下面無(wú)法設(shè)置事件回調(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’)); //連接服務(wù)端 $this->client->connect(’0.0.0.0’, 8888); } public function connect($client) { echo 'connect n'; } public function receive($client, $data) { echo 'server send: {$data}'; //向標(biāo)準(zhǔn)輸出寫(xiě)入數(shù)據(jù) fwrite(STDOUT, '請(qǐng)輸入消息:'); //獲取標(biāo)準(zhǔn)輸入數(shù)據(jù) $msg = trim(fgets(STDIN)); //向服務(wù)端發(fā)送數(shù)據(jù) $client->send($msg); } public function close($client) { echo 'close n'; } public function error($client) { echo 'error n'; }} $cli = new EchoClient();

然后分別運(yùn)行這兩個(gè)腳本

> /data/php56/bin/php server.php> /data/php56/bin/php client.php

運(yùn)行結(jié)果如下:

PHP使用swoole編寫(xiě)簡(jiǎn)單的echo服務(wù)器示例

PHP使用swoole編寫(xiě)簡(jiǎn)單的echo服務(wù)器示例

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php socket用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》及《php程序設(shè)計(jì)算法總結(jié)》

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

標(biāo)簽: PHP
相關(guān)文章:
主站蜘蛛池模板: 呼伦贝尔市| 普陀区| 郓城县| 竹北市| 镇康县| 油尖旺区| 香港 | 乌苏市| 瑞丽市| 双柏县| 阿克苏市| 彩票| 德阳市| 绥宁县| 湘潭县| 文成县| 山西省| 勃利县| 即墨市| 荃湾区| 怀安县| 治县。| 永登县| 安达市| 许昌县| 杭锦旗| 陈巴尔虎旗| 梧州市| 沅江市| 盘山县| 德惠市| 旬邑县| 商南县| 简阳市| 封丘县| 通化县| 嘉定区| 曲阜市| 河西区| 桓仁| 洛川县|