PHP code example of xialeistudio / io

1. Go to this page and download the library: Download xialeistudio/io library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xialeistudio / io example snippets



use io\BinaryStringInputStream;
use io\BinaryStringOutputStream;
use io\DataInputStream;
use io\DataOutputStream;

am();
// 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'


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);