怎么在PHP中使用swoole編寫一個echo服務(wù)器?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

server.php代碼如下:
<?php
class 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'));
//啟動服務(wù)
$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代碼如下:
<?php
class EchoClient {
protected $client = null;
public function __construct() {
//注意這里需設(shè)置為異步,不然下面無法設(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}";
//向標準輸出寫入數(shù)據(jù)
fwrite(STDOUT, "請輸入消息:");
//獲取標準輸入數(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();然后分別運行這兩個腳本
> /data/php56/bin/php server.php > /data/php56/bin/php client.php
運行結(jié)果如下:


看完上述內(nèi)容,你們掌握怎么在PHP中使用swoole編寫一個echo服務(wù)器的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
文章名稱:怎么在PHP中使用swoole編寫一個echo服務(wù)器-創(chuàng)新互聯(lián)
分享URL:http://www.yijiale78.com/article18/phsgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、網(wǎng)站策劃、自適應(yīng)網(wǎng)站、網(wǎng)站導(dǎo)航、小程序開發(fā)、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容