php實現的協議定義

協議定義

  • 首部固定10個字節長度用來保存整個數據包長度,位數不夠補0
  • 數據格式爲xml

數據包樣本

0000000121<?xml version="1.0" encoding="ISO-8859-1"?>
<request>
    <module>user</module>
    <action>getInfo</action>
</request>

其中0000000121代表整個數據包長度,後面緊跟xml數據格式的包體內容

協議實現

namespace Protocols;
class XmlProtocol
{
    public static function input($recv_buffer)
    {
        if(strlen($recv_buffer) < 10)
        {
            // 不夠10字節,返回0繼續等待數據
            return 0;
        }
        // 返回包長,包長包含 頭部數據長度+包體長度
        $total_len = base_convert(substr($recv_buffer, 0, 10), 10, 10);
        return $total_len;
    }

    public static function decode($recv_buffer)
    {
        // 請求包體
        $body = substr($recv_buffer, 10);
        return simplexml_load_string($body);
    }

    public static function encode($xml_string)
    {
        // 包體+包頭的長度
        $total_length = strlen($xml_string)+10;
        // 長度部分湊足10字節,位數不夠補0
        $total_length_str = str_pad($total_length, 10, '0', STR_PAD_LEFT);
        // 返回數據
        return $total_length_str . $xml_string;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章