Linux下搭建swoole服務(wù)的方法

這篇文章主要介紹Linux下搭建swoole服務(wù)的方法,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括鹽池網(wǎng)站建設(shè)、鹽池網(wǎng)站制作、鹽池網(wǎng)頁(yè)制作以及鹽池網(wǎng)絡(luò)營(yíng)銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,鹽池網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到鹽池省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

一、安裝swoole服務(wù)

1.下載swoole源碼,下載地址: https://github.com/swoole/swoole-src/releases

2.將tar包上傳到/usr/local/src/swoole下面,這里面存儲(chǔ)安裝源文件。

3.解壓源文件,tar –xvfswoole.tar

4.進(jìn)入到剛解壓的目錄下輸入命令phpize

5.注意:phpize是php-devel中的東西,它可以給PHP動(dòng)態(tài)添加擴(kuò)展,所以,請(qǐng)確保你的機(jī)器上安裝了php-devel軟件包。

6.接著,依次輸入如下命令:./configure,執(zhí)行編譯檢測(cè)make,編譯swoole

7.缺少pcre和pcre-devel相關(guān)軟件包,安裝上即可。

8.sudo make install

9.php.ini一般在etc下面 編譯安裝成功后,我們還需要修改php.ini,在其中加入swoole.so擴(kuò)展:

10.extension=swoole.so

11.輸入php -m中能查看到swoole說明擴(kuò)展安裝成功。

二、安裝apache啟動(dòng)swoole服務(wù)

(1)測(cè)試是否安裝正確啟動(dòng)swoole Php服務(wù)

(2)在apache中添加server.php文件,和client.php文件。一般目錄在var/www/html下面

(3)打開兩個(gè)終端 在這兩個(gè)文件所在的目錄下面打開這兩個(gè)文件,可以實(shí)現(xiàn)socket長(zhǎng)連接服務(wù)。

安裝lsof:yum -y install lsof

三、配置Server端

class WebSocketService {
 
   private static $instance = NULL;
   public $tagindex = 0;
   public    $server    = null;
   public   $office_cache = null;
   public    $timer_arr = [];    //該變量保存所有的定時(shí)器任務(wù)ID,每一個(gè)客戶端可以通過$timer_arr[客戶端ID]
   得到該客戶端建立的所有定時(shí)器
   public $conf      = [
       'host'            => '0.0.0.0',
       'port'            => 9999,     //服務(wù)使用端口
       'worker_num'      => 2,         //啟動(dòng)worker進(jìn)程數(shù)
       'task_worker_num' => 8,           //啟動(dòng)task進(jìn)程數(shù)
       'is_daemonize'    => 0,          //是否后臺(tái)運(yùn)行:0-否,1-是
       'log_file'        =>'/tmp/swoole_webSocket_server.log',    //日志文件路徑
       'abc'              =>0,
   ];
 
   public function getTagIndex() {
       return $this->conf['abc'];
    }
 
   public function setSetTagIndex($index) {
       $this->conf['abc'] = 100;
       echo $this->getTagIndex();
    }
 
   public function __construct($config = []) {
       $this->office_cache = array('1' => '1', '3'=>'2');
       $this->conf = array_merge($this->conf, (array)$config);
    }
 
   //靜態(tài)方法,返回此類唯一實(shí)例 
   public static function getInstance(){
       if(empty(self::$instance)){ 
           echo "instance \n";
           self::$instance=new WebSocketService(); 
       } 
       return self::$instance; 
    }
 
   /**
    * 服務(wù)器端運(yùn)行webSocket的入口
    */
   public function run() {
       try {
           $this->server = new \swoole_websocket_server($this->conf['host'],$this->conf['port']);
           $this->server->set(
                [
                    'worker_num'      => $this->conf['worker_num'],
                    'task_worker_num' =>$this->conf['task_worker_num'],
                    'daemonize'       => $this->conf['is_daemonize'],
                    'log_file'        => $this->conf['log_file'],
                ]
           );
 
           //注冊(cè)方法列表
           $this->server->on('open', [$this, 'open']);
           $this->server->on('message', [$this, 'message']);
           $this->server->on('task', [$this, 'task']);
           $this->server->on('finish', [$this, 'finish']);
           $this->server->on('close', [$this, 'close']);
 
           $this->server->start();
       } catch (\Exception $e) {
           var_dump($e->getCode() . ':' . $e->getMessage());
       }
 
    }
 
   /**
    * 建立socket鏈接時(shí),執(zhí)行方法
    * @param $server
    * @param $request
    */
   public function open($server, $request) {
       $data = [
           'client_id' => $request->fd,
           'request'   => $request
       ];
       echo 'open<<'.$data['client_id'];
       $this->doOpen($data);
    }
 
   /**
    * 發(fā)送消息時(shí),執(zhí)行方法
    * @param $server
    * @param $frame
    */
   public function message($server, $frame) {
       echo "GET_mesage\n";
       $data = [
           'client_id' => $frame->fd,
           'data'      => $frame->data,
           'frame'     => $frame,
       ];
       $this->doMessage($data);
    }
 
   /**
    * 執(zhí)行具體任務(wù)
    * @param $server
    * @param $task_id
    * @param $from_id
    * @param $data
    */
   public function task($server, $task_id, $from_id, $data) {
       $data['task_id'] = $task_id;
       $data['from_id'] = $from_id;
       $this->doTask($data);
    }
 
   /**
    * 任務(wù)結(jié)果處理
    * @param $server    服務(wù)器對(duì)象
    * @param $taskId    任務(wù)進(jìn)程ID
    * @param $data
    */
   public function finish($server, $taskId, $data) {
       $data['task_id'] = $taskId;
       $this->doFinish($data);
    }
 
   /**
    * 關(guān)閉鏈接
    * @param $server        服務(wù)器對(duì)象
    * @param $client_id     客戶端唯一標(biāo)識(shí)
    */
   public function close($server, $client_id) {
       $data = [
           'client_id' => $client_id
       ];
       $this->doClose($data);
    }
 
   /**
    * 客戶端成功連接到服務(wù)器時(shí),會(huì)觸發(fā)該方法
     * 子類根據(jù)需求重寫該方法
    * @param $data
    * [
    *    'client_id',    //客戶端唯一標(biāo)識(shí)
    *    'data',        //一些請(qǐng)求數(shù)據(jù)
    *    'frame',        //swoole的數(shù)據(jù)
    * ];
    */
   public function doOpen($data) {
       echo "建立連接成功";
 
    }
 
   /**
    * 得到Swoole Websocket Server
    *
    * @return null|\swoole_websocket_server
    */
   public function getServer()
    {
       return $this->server;
    }
 
   /**
    * 收到客戶端發(fā)來的消息,會(huì)觸發(fā)該方法
    * 子類根據(jù)需求重寫該方法
    * @param $data
    * [
    *    'client_id',    //客戶端唯一標(biāo)識(shí)
    *    'data',        //客戶端發(fā)送過來的消息(數(shù)據(jù))
    *    'frame',        //swoole的數(shù)據(jù)
    * ];
    */
   public function doMessage($data) {
       $info = json_decode($data['data'],true);
       $officeid = $info['officeid'];
       $client_id = $data['client_id'];
       echo"<<<<".$officeid.">>>>".$client_id."\r\n";
       if ($officeid == 1) {
           $this->sendMsgToClient('2',array('msg' =>'我是1號(hào)場(chǎng)地發(fā)送給你數(shù)據(jù)'));
       } else {
           $this->sendMsgToClient('1',array('msg' =>'我是3號(hào)場(chǎng)地發(fā)送給你數(shù)據(jù)'));
       }
    }
 
   /**
    * 具體的工作任務(wù)。需要通過 $this->doJob()來觸發(fā)
    * 子類根據(jù)需求重寫該方法
    * @param $data
    * [
    *    'client_id',    //客戶端唯一標(biāo)識(shí)
    * ];
    */
   public function doTask($data) {
    }
 
   /**
    * 工作的結(jié)果處理。
     * 子類根據(jù)需求重寫該方法
    * @param $data
    * [
    *    'client_id',    //客戶端唯一標(biāo)識(shí)
    * ];
    */
   public function doFinish($data) {
    }
 
   /**
    * 客戶端斷開時(shí)會(huì)自動(dòng)觸發(fā)該方法
    * 子類根據(jù)需求重寫該方法
    * @param $data
    * [
    *    'client_id',    //客戶端唯一標(biāo)識(shí)
    * ];
    */
   public function doClose($data) {
    }
 
 
   /**
    * 發(fā)送任務(wù)
    * @param $data    必須是數(shù)組,且要有$data['client_id']
    */
   public function doJob($data) {
       $this->server->task($data);
    }
 
   public function finishJob($data) {
       $this->server->finish($data);
    }
 
   /**
    * 發(fā)送消息到客戶端
    * @param $client_id
    * @param $msg
    */
   public function sendMsgToClient($client_id, $msg) {
       echo "發(fā)送信息給客戶端:{$client_id} | {$msg['action']['name']} | " . date('Y-m-dH:i:s') . "\r\n";
       $this->server->push($client_id, json_encode($msg));
    }
 
   /**
    * 關(guān)閉客戶端鏈接
    * @param $client_id
    */
   public function closeClient($client_id) {
       $this->server->close($client_id);
    }
 
   /**
    * 添加定時(shí)器
    * @param $client_id
    * @param $tick_time
    */
   public function addTimer($client_id, $tick_time) {
       //暫未實(shí)現(xiàn),先使用swoole原生寫法
    }
 
   /**
    * 清除定時(shí)器
    * @param $client_id
    * @param $arr
    */
   public function clearTimer($client_id, &$arr) {
       if (is_array($arr)) {
           foreach ($arr[$client_id] as $val) {
                if (is_array($val)) {
                    foreach ($val as $v) {
                        swoole_timer_clear($v);
                    }
                } else {
                    swoole_timer_clear($val);
                }
           }
       }
       unset($arr[$client_id]);
    }
}

四、配置html前端

$(document).ready(function(){
    varwsurl = "ws://182.92.101.206:9999/";
    console.log(wsurl);
    varwebsocket = new WebSocket(wsurl);
    websocket.onopen= function(evt){
    console.log('Server:  打開WebSocket連接');
    };

    websocket.onclose= function(evt){
           console.log('Server:  關(guān)閉WebSocket連接');
    };

    websocket.onmessage= function(evt){
           varres = JSON.parse(evt.data);
           console.log('Server:  收到消息(來自:'+res+'請(qǐng)求)');
           console.log(res);
    };

    websocket.οnerrοr= function(evt){
           console.log('Server:  出現(xiàn)錯(cuò)誤');
           console.log(evt.data);
    }

    functiondoSend(msg){
           console.log('Client:發(fā)送消息  ' + msg);
           websocket.send(msg);
    }
});

五、啟動(dòng)start.php文件,cd到指定目錄下,然后PHP-CLI運(yùn)行php start.php。這種方式是沒有啟用線程保護(hù)的關(guān)掉后程序結(jié)束線程還在占用。

require'src/WebSocketSwoole/WebSocketService.php';
// require './WebSocketService.php';
session_start();
// $demoService = new\WebSocketSwoole\WebSocketService();
$demoService =\WebSocketSwoole\WebSocketService::getInstance();
$demoService->run();

以上是“Linux下搭建swoole服務(wù)的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

分享名稱:Linux下搭建swoole服務(wù)的方法
分享鏈接:http://muchs.cn/article20/pppjco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、動(dòng)態(tài)網(wǎng)站、全網(wǎng)營(yíng)銷推廣、面包屑導(dǎo)航、品牌網(wǎng)站設(shè)計(jì)、建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作