濮阳杆衣贸易有限公司

主頁 > 知識(shí)庫 > php使用workman框架實(shí)現(xiàn)socket服務(wù)以及連接客戶端

php使用workman框架實(shí)現(xiàn)socket服務(wù)以及連接客戶端

熱門標(biāo)簽:凱立德地鐵站地圖標(biāo)注 天津電銷外呼系統(tǒng)違法嗎 銀行信貸電話機(jī)器人 合肥ai電銷機(jī)器人費(fèi)用 滄州電銷外呼系統(tǒng)價(jià)格 手機(jī)外呼系統(tǒng)什么原理 上海400客服電話怎么申請(qǐng) 400電話個(gè)人能不能辦理 溫州外呼系統(tǒng)招商
  • 1. 解決什么問題,為什么要用workman  socket服務(wù)

   都知道游戲安裝包很大,渠道推廣時(shí),需要對(duì)游戲進(jìn)行分包處理,而PHP命令模式是單進(jìn)程,一次只能分一次包,故這里用workman實(shí)現(xiàn)socket服務(wù)開啟多進(jìn)程,對(duì)游戲進(jìn)行分包處理(一個(gè)進(jìn)程處理一個(gè)分包,多個(gè)進(jìn)程可以同時(shí)處理多個(gè)分包)

  • 2. 服務(wù)端代碼

     server.php

?php
/**
 * 分包程序.切記不能有die或exit出現(xiàn).
 *
 * User: yzm
 * Data: 2018/1/16
 */
 
require_once './vendor/workerman/workerman/Autoloader.php';
require_once './Lib/Function.php';
 
require_once __DIR__ . '/Lib/Db.php';
require_once __DIR__ . '/Lib/DbConnection.php';
require_once __DIR__ . '/Config/Db.php';
 
use Workerman\Worker;
 
// #### create socket and listen 1234 port ####
$tcp_worker = new Worker("tcp://0.0.0.0:9998");
 
/**
 * 定義常量.
 */
define('REP_SUCCESS', 0); // 成功
define('REP_FAIL', -1); // 失敗
define('REP_FAIL_NO_COMPLETED', 1); // 文件未上傳完成
 
 
// 16 processes,與cpu個(gè)數(shù)相同
$tcp_worker->count = 16;
$msg = '';
 
define('ORGPKG', '/Volumes/VMware\ Shared\ Folders/orgpkg/');
define('DISTPKG', '/Volumes/VMware\ Shared\ Folders/');
//define('SYS_IP', '39.108.223.28');
define('SYS_IP', '120.92.142.115');
define('IOS_URL','http://ios.package.tonguu.cn/');
 
 
// Emitted when new connection come
$tcp_worker->onConnect = function ($connection) {
    $connection->sized = 0;
 
    // xcode調(diào)用腳本
    $certMobile = '/mnt/www/DIVIDE_PKG/Cert/%d/mslabEnt.mobileprovision'; // 證書文件
    $shell = "/mnt/www/DIVIDE_PKG/Lib/dividePkg/resign  sign -ipapath  %s  -destpath %s  -pppath %s -agentid %s";
 
    $connection->shell = $shell;
    $connection->pppath = $certMobile;
 
    echo date("Y-m-d H:i:s") . " connect!" . getclientip() . PHP_EOL;
 
};
 
/**
 * 響應(yīng)結(jié)果.
 *
 * @author yzm
 */
function resonse($conn, $msg, $error = REP_FAIL, $data = [])
{
    $res = ['msg' => $msg, 'error' => intval($error)];
    if (!empty($data)) {
        $res['content'] = $data;
    }
 
    debug($res);
 
    // 返回JSON數(shù)據(jù)格式到客戶端 包含狀態(tài)信息
    $rst = json_encode($res);
 
    $conn->send($rst);
}
 
 
// Emitted when data received
$tcp_worker->onMessage = function ($connection, $data) {
    set_time_limit(0);
    ini_set('memory_limit', -1);
 
    $db = \Lib\Db::instance('btmox');
    $data = @json_decode($data, true);
 
    try{
        if (empty($data['authId'])) {
            throw new \Exception('授權(quán)文件參數(shù)錯(cuò)誤');
        }
 
        //1. 查詢所有待分包的ios渠道包
        $iosPkg = $db
            ->select('a.id,a.vid,a.filename,a.agent,d.pinyin,b.name,c.package_name')
            ->from('cy_ct_ios_package a')
            ->where("a.status=0 AND c.is_send=1")
            ->leftJoin('cy_ct_ios_mobileversion b','b.id=a.m_v_id')
            ->rightJoin('cy_ct_ios_version c','c.id=a.vid')
            ->leftJoin('cy_game d','d.id=c.game_id')
            ->orderByASC(['a.create_time'])->query();
 
        if(empty($iosPkg)) throw new \Exception('沒有需要待分包的數(shù)據(jù)'.PHP_EOL);
 
        //2. 分包
        foreach($iosPkg as $one){
            try{
                //對(duì)當(dāng)前正要分的包把狀態(tài)改為‘分包中'
                $db->update('cy_ct_ios_package')->cols([
                    'status' => 2,
                ])->where("id=".$one['id'])->query();
 
                $filename = $one['pinyin'];
                // 渠道分包
                $verId = @$one['vid'];
                $agent = @$one['agent'];
                $location = isset($data['location']) ? $data['location'] : 1;
                $authId = @intval($data['authId']); // 授權(quán)文件
 
                if (empty($verId) || empty($agent)) {
                    throw new \Exception("分包失?。?.$one['id']."版本、渠道為空\(chéng)r\n");
                }
 
                // 替換\,否則PHP驗(yàn)證不文件是否存在
                $orgPkg = str_replace('\\', '', ORGPKG) . "{$filename}.ipa";
 
                debug($one['id'].'原包:' . $orgPkg);
 
                debug($one['id'].'是否是文件:' . is_file($orgPkg));
 
                if (!is_file($orgPkg)) {
                    throw new \Exception("分包失?。?.$one['id']."母包不存在-$orgPkg\r\n");
                }
 
                // 從新拼接文件
                $orgPkg = ORGPKG . "{$filename}.ipa";
 
                // 獲取目標(biāo)包存放路徑
                $distPkgPath = getDistPkgPath($location);
 
                $distPkg = $distPkgPath . "$filename/vers_{$verId}/{$filename}_$agent.ipa";
                debug('渠道分包地址:' . $distPkg);
                if (file_exists($filename)) {
                    @unlink($filename);
                }
 
                // 替換授權(quán)文件
                $certMobile = sprintf($connection->pppath, $authId);
 
                // 渠道分包
                list($msg, $code) = dividePkg($connection->shell, $orgPkg, $distPkg, $agent, $certMobile);
 
                debug('$code' . $code);
 
                if ($code != 0) {
                    throw new \Exception("分包失?。?.$msg."\r\n");
                }
 
                $distPkg = str_replace($distPkgPath, '', $distPkg);
 
            }catch (\Exception $ex){
                debug($ex->getMessage());
                $code = -1;
                $msg = $ex->getMessage();
            }
 
            //3. 分包后更新分包結(jié)果,狀態(tài),下載地址
            $status = $code == 0 ? 1 : 2;
            $sdata['status'] = $status;
            $sdata['message'] = $msg;
            if($status == 1){
                $sdata['url'] = IOS_URL.$distPkg;
            }
            $db->update('cy_ct_ios_package')->cols($sdata)->where("id=".$one['id'])->query();
        }
 
        resonse($connection, $msg,$code);
    }catch (\Exception  $ex){
        resonse($connection, $ex->getMessage());
    }
};
 
// Emitted when new connection come
$tcp_worker->onClose = function ($connection) {
    echo date("Y-m-d H:i:s") . " closed!" . PHP_EOL;
};
 
Worker::runAll();
  • 3. 客戶端代碼

   client.php

?php
 
/**
 * 讀取socket數(shù)據(jù).
 *
 * @author yzm
 *
 * @param $socket
 * @param bool|true $isDividePkg
 * @return array|null|string
 */
function socketRead($socket, $isDividePkg = true)
{
    $rst = null;
 
    $buf = socket_read($socket, 8192);
    if ($isDividePkg) {
        $_buf = @json_decode($buf, true);
        $rst = !empty($_buf) ? [$_buf['error'], $_buf['msg'], @$_buf['content']] : $buf;
    } else {
        $rst = $buf;
    }
 
    return $rst;
}
 
/**
 * 向物理機(jī)發(fā)起socket請(qǐng)求.
 *
 * @param $args 參數(shù)
 * @return bool
 * @throws \Exception
 */
function sendSocket($args)
{
    set_time_limit(0);
    ini_set('memory_limit', -1);
 
    $type = isset($args['type']) ? $args['type'] : 0;
 
    if (!$type) throw new \Exception('類型參數(shù)錯(cuò)誤');
 
    $port = 9998;
    $ip = "127.0.0.1";
 
    // 創(chuàng)建socket
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 
    if ($socket = 0) throw new \Exception('創(chuàng)建socket失敗,REASON:' . socket_strerror($socket));
 
    try {
 
        // 連接服務(wù)器
        $result = socket_connect($socket, $ip, $port);
        if ($result  0 || is_null($result) || !$result) throw new \Exception('連接失敗,REASON:' . socket_strerror($result));
 
        $in = json_encode($args);
 
        // 寫入文件信息
        if (!socket_write($socket, $in, strlen($in))) throw new \Exception('消息發(fā)送失敗,REASON:' . socket_strerror($socket));
 
        // 讀取socket返回的數(shù)據(jù)
        list($error, $msg, $data) = socketRead($socket);
 
        if ($type != 3  $error != 0) throw new \Exception('104服務(wù)器異常,REASON:' . $msg);
 
        // 關(guān)閉socket
        socket_close($socket);
 
        switch ($type) {
            case 2: // 分包
                $rst = $data['url'];
                break;
            case 3: // 檢測(cè)文件
                if ($error == -1) {
                    throw new \Exception('檢測(cè)文件失敗,REASON:' . $msg);
                }
 
                $rst = $error;
                break;
            default:
                $rst = true;
                break;
        }
 
    } catch (\Exception $ex) {
 
        // 關(guān)閉socket
        @socket_close($socket);
 
        throw new \Exception($ex->getMessage());
    }
 
    return $rst;
}
 
 
/**
 * 分包程序.切記不能有die或exit出現(xiàn).
 *
 * User: yzm
 * Data: 2018/1/16
 */
require_once './Lib/Function.php';
 
$i=0;
while ($i30){
    try{
        $data['type'] = 1;
        $data['authId'] = 2;
        $data['location'] = 1;
        sendSocket($data);
    }catch (\Exception $ex){
        echo $ex->getMessage();
    }
    $i++;
    sleep(5);
}
 
  • 4. 使用

    a. 開啟服務(wù)

        php server.php start  //可以看到開啟了多個(gè)進(jìn)程

   b. 客戶端連接

       php client.php  //從代碼知道,里頭用了循環(huán),可以多次連接服務(wù),同時(shí)發(fā)送數(shù)據(jù),服務(wù)端會(huì)把結(jié)果返回

到此這篇關(guān)于php使用workman框架實(shí)現(xiàn)socket服務(wù)以及連接客戶端的文章就介紹到這了,更多相關(guān)php使用workman內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • PHP實(shí)現(xiàn)兩種排課方式
  • 詳細(xì)分析PHP7與PHP5區(qū)別
  • php生成用戶密碼的兩種方式
  • php類中static與self的使用區(qū)別淺析
  • php如何用PDO操作大數(shù)據(jù)對(duì)象

標(biāo)簽:金華 怒江 酒泉 赤峰 七臺(tái)河 洛陽 溫州 白城

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php使用workman框架實(shí)現(xiàn)socket服務(wù)以及連接客戶端》,本文關(guān)鍵詞  php,使用,workman,框架,實(shí)現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《php使用workman框架實(shí)現(xiàn)socket服務(wù)以及連接客戶端》相關(guān)的同類信息!
  • 本頁收集關(guān)于php使用workman框架實(shí)現(xiàn)socket服務(wù)以及連接客戶端的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    海晏县| 邵阳县| 灯塔市| 通化市| 额济纳旗| 陆川县| 安康市| 桑日县| 敖汉旗| 赤峰市| 澄城县| 子洲县| 德令哈市| 贵港市| 偃师市| 玛多县| 沈丘县| 高要市| 定日县| 南岸区| 嘉善县| 永宁县| 沙河市| 班戈县| 姜堰市| 漾濞| 阆中市| 吉木乃县| 江城| 子长县| 乐平市| 永平县| 象山县| 通渭县| 大同市| 阿巴嘎旗| 合肥市| 定兴县| 定安县| 湘潭市| 保山市|