1. 程式人生 > >ThinkPHP5中使用Workerman框架

ThinkPHP5中使用Workerman框架

workerman thinkphp5 tcp通信 php之socket通信

ThinkPHP框架不多說,強悍之處不容置疑。有疑問看官方手冊

Workerman框架也是非常強悍的(開發框架人的背景不是很清楚),官方是這樣介紹的:

Workerman,讓你看到PHP不為人知的一面。
當然詳細的介紹WM官方也給出了非常詳細的手冊。
這裏也並不打算長篇的介紹和吹噓TP與WM的強悍的話。
以前在使用TP3.2.3的時候,就接觸使用了Workerman框架,但當時TP官方並沒有把WM集成進來,
也就分開獨立使用兩個框架了,各司其職。
現在TP5中已經把WM作為擴展集成進來了。

集成步驟也請看TP5的手冊:

https://www.kancloud.cn/manual/thinkphp5/235128

下面把TP5官方給出的示例代碼:
<?php
namespace app\index\controller;

use think\worker\Server;
use Workerman\Lib\Timer; // 引入WM框架的類庫,

class Worker extends Server
{
//     protected $socket = ‘http://0.0.0.0:2348‘;
    protected $socket = ‘tcp://0.0.0.0:2349‘;

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        // 給connection臨時設置一個lastMessageTime屬性,用來記錄上次收到消息的時間
        $connection->lastMessageTime = time();
        
        $connection->send(json_encode($data));
        $connection->send(‘我收到你的信息了‘);
    }
    
    /**
     * 當連接建立時觸發的回調函數
     * @param $connection
     */
    public function onConnect($connection)
    {
        echo $connection->getRemoteIP();
    }
    
    /**
     * 當連接斷開時觸發的回調函數
     * @param $connection
     */
    public function onClose($connection)
    {
        echo $connection->id . ‘disconnect \r\n‘;
    }
    
    /**
     * 當客戶端的連接上發生錯誤時觸發
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }
    
    /**
     * 每個進程啟動
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        // 進程啟動後設置一個每秒運行一次的定時器
        Timer::add(1, function ()use($worker){
            $time_now = time();
            foreach ($worker->connections as $connection) {
                // 有可能該connection還沒收到過消息,則lastMessageTime設置為當前時間
                if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                    continue;
                }
                // 上次通訊時間間隔大於心跳間隔,則認為客戶端已經下線,關閉連接
                if ($time_now - $connection->lastMessageTime > 10) {
                    $connection->close();
                }
            }
        });
        echo $worker->id . "\r\n";
    }
}
這個示例是用來作為TCP協議開發的,看onMessage、onWorkerStart兩個函數,是增加一個定時器,
因為是做TCP服務端,必須要使用心跳來檢測客戶端是否因極端情況(斷電、異常關機)
而導致斷開(這種狀況服務端是無法立即得知客戶端的斷開狀態的)。
實現的邏輯是Worker類繼承Server類,Worker類中給參數賦值,
然後由父類的Server構造函數來實例化Worker對象,

------------------------------------------------------------

Server.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]
/* */> // +---------------------------------------------------------------------- namespace think\worker; use Workerman\Worker; use Workerman\Lib\Timer; /** * Worker控制器擴展類 */ abstract class Server { protected $worker; protected $worker2; protected $socket = ‘‘; protected $protocol = ‘http‘; protected $host = ‘0.0.0.0‘; protected $port = ‘2346‘; protected $processes = 1; /** * 架構函數 * @access public */ public function __construct() { // 實例化 Websocket 服務 $this->worker = new Worker($this->socket ?: $this->protocol . ‘://‘ . $this->host . ‘:‘ . $this->port); // $this->worker2 = new Worker(‘tcp://0.0.0.0:2349‘); // 設置進程數 $this->worker->count = $this->processes; // 設置進程名稱 $this->worker->name = "bluetooth"; // 初始化 $this->init(); // 設置回調 foreach ([‘onWorkerStart‘, ‘onConnect‘, ‘onMessage‘, ‘onClose‘, ‘onError‘, ‘onBufferFull‘, ‘onBufferDrain‘, ‘onWorkerStop‘, ‘onWorkerReload‘] as $event) { if (method_exists($this, $event)) { $this->worker->$event = [$this, $event]; } } // Run worker Worker::runAll(); } protected function init() { } }

雖然是集成進來,但依舊很靈活,可以在Server.php裏面自定義你所需要的任意WM功能。

本文出自 “為了以後” 博客,謝絕轉載!

ThinkPHP5中使用Workerman框架