一些例子
例子一
協(xié)議定義
- 首部固定10個(gè)字節(jié)長度用來保存整個(gè)數(shù)據(jù)包長度,位數(shù)不夠補(bǔ)0
- 數(shù)據(jù)格式為xml
數(shù)據(jù)包樣本
0000000121<?xml version="1.0" encoding="ISO-8859-1"?>
<request>
<module>user</module>
<action>getInfo</action>
</request>
其中0000000121代表整個(gè)數(shù)據(jù)包長度,后面緊跟xml數(shù)據(jù)格式的包體內(nèi)容
協(xié)議實(shí)現(xiàn)
namespace Protocols;
class XmlProtocol
{
public static function input($recv_buffer)
{
if(strlen($recv_buffer) < 10)
{
// 不夠10字節(jié),返回0繼續(xù)等待數(shù)據(jù)
return 0;
}
// 返回包長,包長包含 頭部數(shù)據(jù)長度+包體長度
$total_len = base_convert(substr($recv_buffer, 0, 10), 10, 10);
return $total_len;
}
public static function decode($recv_buffer)
{
// 請(qǐng)求包體
$body = substr($recv_buffer, 10);
return simplexml_load_string($body);
}
public static function encode($xml_string)
{
// 包體+包頭的長度
$total_length = strlen($xml_string)+10;
// 長度部分湊足10字節(jié),位數(shù)不夠補(bǔ)0
$total_length_str = str_pad($total_length, 10, '0', STR_PAD_LEFT);
// 返回?cái)?shù)據(jù)
return $total_length_str . $xml_string;
}
}
例子二
協(xié)議定義
- 首部4字節(jié)網(wǎng)絡(luò)字節(jié)序unsigned int,標(biāo)記整個(gè)包的長度
- 數(shù)據(jù)部分為Json字符串
數(shù)據(jù)包樣本
****{"type":"message","content":"hello all"}
其中首部四字節(jié)*號(hào)代表一個(gè)網(wǎng)絡(luò)字節(jié)序的unsigned int數(shù)據(jù),為不可見字符,緊接著是Json的數(shù)據(jù)格式的包體數(shù)據(jù)
協(xié)議實(shí)現(xiàn)
namespace Protocols;
class JsonInt
{
public static function input($recv_buffer)
{
// 接收到的數(shù)據(jù)還不夠4字節(jié),無法得知包的長度,返回0繼續(xù)等待數(shù)據(jù)
if(strlen($recv_buffer)<4)
{
return 0;
}
// 利用unpack函數(shù)將首部4字節(jié)轉(zhuǎn)換成數(shù)字,首部4字節(jié)即為整個(gè)數(shù)據(jù)包長度
$unpack_data = unpack('Ntotal_length', $recv_buffer);
return $unpack_data['total_length'];
}
public static function decode($recv_buffer)
{
// 去掉首部4字節(jié),得到包體Json數(shù)據(jù)
$body_json_str = substr($recv_buffer, 4);
// json解碼
return json_decode($body_json_str, true);
}
public static function encode($data)
{
// Json編碼得到包體
$body_json_str = json_encode($data);
// 計(jì)算整個(gè)包的長度,首部4字節(jié)+包體字節(jié)數(shù)
$total_length = 4 + strlen($body_json_str);
// 返回打包的數(shù)據(jù)
return pack('N',$total_length) . $body_json_str;
}
}
例子三(使用二進(jìn)制協(xié)議上傳文件)
協(xié)議定義
struct
{
unsigned int total_len; // 整個(gè)包的長度,大端網(wǎng)絡(luò)字節(jié)序
char name_len; // 文件名的長度
char name[name_len]; // 文件名
char file[total_len - BinaryTransfer::PACKAGE_HEAD_LEN - name_len]; // 文件數(shù)據(jù)
}
協(xié)議樣本
*****logo.png******************
其中首部四字節(jié)*號(hào)代表一個(gè)網(wǎng)絡(luò)字節(jié)序的unsigned int數(shù)據(jù),為不可見字符,第5個(gè)*是用一個(gè)字節(jié)存儲(chǔ)文件名長度,緊接著是文件名,接著是原始的二進(jìn)制文件數(shù)據(jù)
協(xié)議實(shí)現(xiàn)
namespace Protocols;
class BinaryTransfer
{
// 協(xié)議頭長度
const PACKAGE_HEAD_LEN = 5;
public static function input($recv_buffer)
{
// 如果不夠一個(gè)協(xié)議頭的長度,則繼續(xù)等待
if(strlen($recv_buffer) < self::PACKAGE_HEAD_LEN)
{
return 0;
}
// 解包
$package_data = unpack('Ntotal_len/Cname_len', $recv_buffer);
// 返回包長
return $package_data['total_len'];
}
public static function decode($recv_buffer)
{
// 解包
$package_data = unpack('Ntotal_len/Cname_len', $recv_buffer);
// 文件名長度
$name_len = $package_data['name_len'];
// 從數(shù)據(jù)流中截取出文件名
$file_name = substr($recv_buffer, self::PACKAGE_HEAD_LEN, $name_len);
// 從數(shù)據(jù)流中截取出文件二進(jìn)制數(shù)據(jù)
$file_data = substr($recv_buffer, self::PACKAGE_HEAD_LEN + $name_len);
return array(
'file_name' => $file_name,
'file_data' => $file_data,
);
}
public static function encode($data)
{
// 可以根據(jù)自己的需要編碼發(fā)送給客戶端的數(shù)據(jù),這里只是當(dāng)做文本原樣返回
return $data;
}
}
服務(wù)端協(xié)議使用示例
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('BinaryTransfer://0.0.0.0:8333');
// 保存文件到tmp下
$worker->onMessage = function(TcpConnection $connection, $data)
{
$save_path = '/tmp/'.$data['file_name'];
file_put_contents($save_path, $data['file_data']);
$connection->send("upload success. save path $save_path");
};
Worker::runAll();
客戶端文件 client.php (這里用php模擬客戶端上傳)
<?php
/** 上傳文件客戶端 **/
// 上傳地址
$address = "127.0.0.1:8333";
// 檢查上傳文件路徑參數(shù)
if(!isset($argv[1]))
{
exit("use php client.php \$file_path\n");
}
// 上傳文件路徑
$file_to_transfer = trim($argv[1]);
// 上傳的文件本地不存在
if(!is_file($file_to_transfer))
{
exit("$file_to_transfer not exist\n");
}
// 建立socket連接
$client = stream_socket_client($address, $errno, $errmsg);
if(!$client)
{
exit("$errmsg\n");
}
// 設(shè)置成阻塞
stream_set_blocking($client, 1);
// 文件名
$file_name = basename($file_to_transfer);
// 文件名長度
$name_len = strlen($file_name);
// 文件二進(jìn)制數(shù)據(jù)
$file_data = file_get_contents($file_to_transfer);
// 協(xié)議頭長度 4字節(jié)包長+1字節(jié)文件名長度
$PACKAGE_HEAD_LEN = 5;
// 協(xié)議包
$package = pack('NC', $PACKAGE_HEAD_LEN + strlen($file_name) + strlen($file_data), $name_len) . $file_name . $file_data;
// 執(zhí)行上傳
fwrite($client, $package);
// 打印結(jié)果
echo fread($client, 8192),"\n";
客戶端使用示例
命令行中運(yùn)行 php client.php <文件路徑>
例如 php client.php abc.jpg
例子四(使用文本協(xié)議上傳文件)
協(xié)議定義
json+換行,json中包含了文件名以及base64_encode編碼(會(huì)增大1/3的體積)的文件數(shù)據(jù)
協(xié)議樣本
{"file_name":"logo.png","file_data":"PD9waHAKLyo......"}\n
注意末尾為一個(gè)換行符,在PHP中用雙引號(hào)字符"\n"
標(biāo)識(shí)
協(xié)議實(shí)現(xiàn)
namespace Protocols;
class TextTransfer
{
public static function input($recv_buffer)
{
$recv_len = strlen($recv_buffer);
if($recv_buffer[$recv_len-1] !== "\n")
{
return 0;
}
return strlen($recv_buffer);
}
public static function decode($recv_buffer)
{
// 解包
$package_data = json_decode(trim($recv_buffer), true);
// 取出文件名
$file_name = $package_data['file_name'];
// 取出base64_encode后的文件數(shù)據(jù)
$file_data = $package_data['file_data'];
// base64_decode還原回原來的二進(jìn)制文件數(shù)據(jù)
$file_data = base64_decode($file_data);
// 返回?cái)?shù)據(jù)
return array(
'file_name' => $file_name,
'file_data' => $file_data,
);
}
public static function encode($data)
{
// 可以根據(jù)自己的需要編碼發(fā)送給客戶端的數(shù)據(jù),這里只是當(dāng)做文本原樣返回
return $data;
}
}
服務(wù)端協(xié)議使用示例
說明:寫法與二進(jìn)制上傳寫法一樣,即能做到幾乎不用改動(dòng)任何業(yè)務(wù)代碼便可以切換協(xié)議
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('TextTransfer://0.0.0.0:8333');
// 保存文件到tmp下
$worker->onMessage = function(TcpConnection $connection, $data)
{
$save_path = '/tmp/'.$data['file_name'];
file_put_contents($save_path, $data['file_data']);
$connection->send("upload success. save path $save_path");
};
Worker::runAll();
客戶端文件 textclient.php (這里用php模擬客戶端上傳)
<?php
/** 上傳文件客戶端 **/
// 上傳地址
$address = "127.0.0.1:8333";
// 檢查上傳文件路徑參數(shù)
if(!isset($argv[1]))
{
exit("use php client.php \$file_path\n");
}
// 上傳文件路徑
$file_to_transfer = trim($argv[1]);
// 上傳的文件本地不存在
if(!is_file($file_to_transfer))
{
exit("$file_to_transfer not exist\n");
}
// 建立socket連接
$client = stream_socket_client($address, $errno, $errmsg);
if(!$client)
{
exit("$errmsg\n");
}
stream_set_blocking($client, 1);
// 文件名
$file_name = basename($file_to_transfer);
// 文件二進(jìn)制數(shù)據(jù)
$file_data = file_get_contents($file_to_transfer);
// base64編碼
$file_data = base64_encode($file_data);
// 數(shù)據(jù)包
$package_data = array(
'file_name' => $file_name,
'file_data' => $file_data,
);
// 協(xié)議包 json+回車
$package = json_encode($package_data)."\n";
// 執(zhí)行上傳
fwrite($client, $package);
// 打印結(jié)果
echo fread($client, 8192),"\n";
客戶端使用示例
命令行中運(yùn)行 php textclient.php <文件路徑>
例如 php textclient.php abc.jpg