用户友好的二进制数据操作库
1.0.0
2020-01-17 09:04 UTC
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is auto-updated.
Last update: 2024-09-17 20:22:51 UTC
README
用户友好的二进制数据操作库。
正如您所知,pack
/unpack
在操作二进制数据时并不友好,这就是为什么这个项目被开发出来的原因。
您可以使用这个项目来开发二进制协议客户端(例如 kafka、memcached 等...)
安装
composer require xialeistudio/io
功能
- 操作二进制字符串
- 操作文件资源(例如文件、套接字等)
支持的数据类型
所有数字都支持大端和小端
示例
二进制字符串示例
此示例简单地使用二进制字符串在内存中操作数据。
<?php use io\BinaryStringInputStream; use io\BinaryStringOutputStream; use io\DataInputStream; use io\DataOutputStream; require __DIR__.'/vendor/autoload.php'; // use binary string as underlying stream, you can simply change to FileOutputStream. $out = new BinaryStringOutputStream(); // wrap underlying stream, so you can operate many data types instead of byte. $dataOut = new DataOutputStream($out); $dataOut->writeUnSignedIntBE(0x12345678); $dataOut->writeUnSignedShortBE(0x1234); $dataOut->writeString('hello'); // output final binary data // hex data: 0x12 0x34 0x56 0x78 0x12 0x34 0x68 0x65 0x6c 0x6c 0x6f $data = $out->toBinaryString(); // create data input stream from binary stream data, you can simply change to FileInputStream. $in = new DataInputStream(new BinaryStringInputStream($data)); $int = $in->readUnSignedIntBE(); // hex data: 0x12 0x34 0x56 0x78 $short = $in->readUnSignedShortBE(); // hex data: 0x12 0x34 $string = $in->readString(5); // read 5 chars, $string is 'hello'
文件流示例
此示例简单地通过套接字连接发送/接收二进制数据。
<?php use io\DataInputStream; use io\DataOutputStream; use io\FileInputStream; use io\FileOutputStream; $client = stream_socket_client('tcp://127.0.0.1:10000', $errno, $errstr); if($errno) { die($errstr); } // send binary data to server, this example use a private protocol. // wrap socket resource $out = new DataOutputStream(new FileOutputStream($client)); // write header part $out->writeUnSignedShortBE(0xcafe); // magic number $out->writeUnSignedShortBE(0x0001); // version number $out->writeUnSignedIntBE(0x00000007); // body length 2 bytes opcode + 5 bytes string // write body part $out->writeUnSignedShortBE(0x0001); // opcode $out->writeString('hello'); // 5 bytes string $out->flush(); // receive response from server $in = new DataInputStream(new FileInputStream($client)); $magicNumber = $in->readUnSignedShortBE(); // magic number $versionNumber = $in->readUnSignedShortBE(); // version number $bodyLength = $in->readUnSignedIntBE(); // body length; $opcode = $in->readUnSignedShortBE(); // opcode $string = $in->readString($bodyLength - $opcode);
Kafka元数据请求
examples/get_kafka_brokers.php
展示了如何与 kafka 通信。