text協(xié)議
Workerman定義了一種叫做text的文本協(xié)議,協(xié)議格式為
數(shù)據(jù)包+換行符
,即在每個(gè)數(shù)據(jù)包末尾加上一個(gè)換行符表示包的結(jié)束。
例如下面的buffer1和buffer2字符串符合text協(xié)議:
// 文本加一個(gè)回車
$buffer1 = 'abcdefghijklmn
';
// 在php中雙引號中的\n代表一個(gè)換行符,例如"\n"
$buffer2 = '{"type":"say", "content":"hello"}'."\n";
// 與服務(wù)端建立socket連接
$client = stream_socket_client('tcp://127.0.0.1:5678');
// 以text協(xié)議發(fā)送buffer1數(shù)據(jù)
fwrite($client, $buffer1);
// 以text協(xié)議發(fā)送buffer2數(shù)據(jù)
fwrite($client, $buffer2);
text協(xié)議非常簡單易用,如果開發(fā)者需要一個(gè)屬于自己的協(xié)議,例如與手機(jī)App傳輸數(shù)據(jù)或者與硬件通訊等等,可以考慮使用text協(xié)議,開發(fā)調(diào)試都非常方便。
text協(xié)議調(diào)試
text協(xié)議可以使用telnet客戶端調(diào)試,例如下面的例子:
新建文件test.php
require_once __DIR__ . '/Workerman/Autoloader.php';
use Workerman\Worker;
$text_worker = new Worker("text://0.0.0.0:5678");
$text_worker->onMessage = function($connection, $data)
{
var_dump($data);
$connection->send("hello world");
};
Worker::runAll();
執(zhí)行php test.php start
顯示如下
php test.php start
Workerman[test.php] start in DEBUG mode
----------------------- WORKERMAN -----------------------------
Workerman version:3.2.7 PHP version:5.4.37
------------------------ WORKERS -------------------------------
user worker listen processes status
root none myTextProtocol://0.0.0.0:5678 1 [OK]
----------------------------------------------------------------
Press Ctrl-C to quit. Start success.
重新打開一個(gè)終端,利用telnet測試(建議用linux系統(tǒng)的telnet)
假設(shè)是本機(jī)測試,
終端執(zhí)行 telnet 127.0.0.1 5678
然后輸入 hi回車
會接收到數(shù)據(jù)hello world\n
telnet 127.0.0.1 5678
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hi
hello world