swoole+thinkphp5搭建socket請求

目錄

         1、下載源碼

2、搭建環境

3、開啓服務

4、websocket請求

5、ajax正常請求

6、驗證


1、下載源碼

源碼地址:https://github.com/imgaoxianshen/swoole_thinkphp.git 

下載之後我更改以下兩處代碼 Application\index\controller\index.php 、server\ws.php  可以複製對應修改一下:      

<?php
namespace app\index\controller;
use app\common\lib\Util;
use app\common\lib\ali\Sms;

class Index
{
    public function index()
    {
        if(empty($_GET['game_id'])){
            return Util::show(config('code.error'),'error1');
        }
        if(empty($_GET['content'])){
            return Util::show(config('code.error'),'error2');
        }
        $data = [
            'user' => '用戶'.rand(0,2000),
            'content' =>$_GET['content']
        ];
        foreach($_POST['http_server']->ports[1]->connections as $fd){
            $_POST['http_server']->push($fd,json_encode($data));
        }
        return Util::show(config('code.success'),'success',$data);
    }

    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }

    public function sms(){
        try{
            $res = Sms::sendSms(15669762297,123456);
            dump($res);
        }catch(\Exception $e){
            echo $e->getMessage();
        }
    }
}
<?php
class Ws{
    CONST HOST = "0.0.0.0";
    CONST PORT = 9501;
    CONST CHART_PORT = 8812;
    public $ws = null;
    public function __construct(){
        $this->ws = new swoole_websocket_server(self::HOST,self::PORT);
        
        $this->ws->listen(self::HOST,self::CHART_PORT,SWOOLE_SOCK_TCP);

        $this->ws->set([
            'document_root' => "/home/root/default/swoole/public/static",
            'enable_static_handler' => true,
            'worker_num' => 5,
            'task_worker_num' =>4
        ]);
        $this->ws->on('start',[$this,'onStart']);
        $this->ws->on('workerstart',[$this,'onWorkerStart']);
        $this->ws->on('request',[$this,'onRequest']);
        $this->ws->on('open',[$this,'onOpen']);
        $this->ws->on('message',[$this,'onMessage']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onClose']);
        $this->ws->start();
    }

    public function onWorkerStart(swoole_server $server,$worker_id){
        define("APP_PATH",__DIR__."/../application/");
        require __DIR__."/../thinkphp/start.php";
    }

    public function onStart($server){
        //進程名字
        swoole_set_process_name("live_master");
    }
    

    public function onRequest($request,$response){
        //防止谷歌瀏覽器默認訪問圖標
        if($request->server['request_uri'] =='/favicon.ico'){
            $response->status(404);
            $response->end();
            return;
        }
        $_SERVER = [];
        if(isset($request->server)){
            foreach($request->server as $k=>$v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if(isset($request->header)){
            foreach($request->header as $k=>$v){
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        $_GET = [];
        if(isset($request->get)){
            foreach($request->get as $k=>$v){
                $_GET[$k] = $v;
            }
        }
        $_FILES = [];
        if(isset($request->files)){
            foreach($request->files as $k=>$v){
                $_FILES[$k] = $v;
            }
        }
        $_POST = [];
        if(isset($request->post)){
            foreach($request->post as $k=>$v){
                $_POST[$k] = $v;
            }
        }
        
        $_POST['http_server'] = $this->ws;
        //緩衝區
        ob_start();
        try{
            think\Container::get('app', [APP_PATH])
            ->run()
            ->send();
        }catch(\Exception $e){
            //todo
        }
        $res = ob_get_contents();
        ob_end_clean();
        $response->end($res);
    }

    public function onTask($serv,$taskId,$workerId,$data){
        //分發task任務 
        $obj = new \app\common\lib\task\Task;
        $method =  $data['method'];
        $flag = $obj->$method($data['data'],$serv);
        return $flag;
    }

    public function onFinish($serv, $task_id, $data){
        dump($data);
    }

    public function onOpen($ws,$req){
        //fd作爲有序集合放入redis中
        var_dump($req->fd);
    }

    public function onMessage($ws,$frame){
        echo $frame->fd;
        $ws->push($frame->fd,"server-push");
    }

    public function onClose($ws,$fd){
        var_dump($fd);
    }
}

new Ws();

 

如果自己感興趣可以參考以下視頻教程自己親自來搭建thinkphp5+swoole  

地址:https://pan.baidu.com/s/1-y5h1oI99z2afxiqc7YCcA 提取碼: huy9 

 

 

2、搭建環境

條件不允許的情況下可以在自己的筆記本電腦上安裝 vagrant+virturebox+lnmp+swoole,還有php的swoole拓展。(這一步就像自己搭建一個php的本地開發環境一樣,自己親手來搭建,這裏就不做具體說明了)

 

3、開啓服務

搭建好環境把第1步下載的文件放在你本地配置的虛擬機linux的自定義或者你想放的文件夾下。找到根目錄的server這個文件夾下的ws.php文件,使用php ws.php命令來執行這個ws.php文件。

 

4、websocket請求

服務開啓之後,在利用js寫一個前端的websocket請求,我的本地html參考代碼如下(ws://192.168.33.10:8812/?s=index/index/index這個地址可以根據你自己的請求url來更換)index.html

<html>
<head>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
// 初始化一個 WebSocket 對象

var wsObj = new WebSocket("ws://192.168.33.10:8812/?s=index/index/index");   //建立連接
    wsObj.onopen = function(){  //發送請求
        console.log("open");
        wsObj.send("Hello WebSocket");
    };
    wsObj.onmessage = function(ev){  //獲取後端響應
        console.log(ev.data);
    };
    wsObj.onclose = function(ev){
        alert("close");
    };
    wsObj.onerror = function(ev){
        alert("error");
    };
</script>
</body>
</html>

 

5、ajax正常請求

在寫一個前端請求後端接口的 ajax請求html,我的請求代碼如下 request.html

<html>
<head>
</head>
<body>
   <button οnclick='request()'>提交</button>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
	function request(){
		$.ajax({
		    type:"POST",    //請求方式
		    url:"http://192.168.33.10:9501/index/index/index",
		    dataType:"jsonp",    //跨域json請求一定是jsonp
		    jsonp: "callbackparam",    //跨域請求的參數名,默認是callback
		    data:{'content':'ceshi','game_id':1},   //請求參數
		    beforeSend: function() {
		        //請求前的處理
		    },
		    success: function(data) {
		    	console.log(data);
		        //請求成功處理,和本地回調完全一樣
		    },
		    complete: function() {
		        //請求完成的處理
		    },
		    error: function() {
		        //請求出錯處理
		    }
		});
	}
</script>
</html>

 

6、驗證

驗證第5步ajax請求之後,websocket連接的頁面是否會收到ajax請求傳送的數據

 

 (1)打開index.html

 

 

(2)打開request.html

 

 

(3)打開index.html查看

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章