Skip to content

Instantly share code, notes, and snippets.

@scr34m
Last active July 6, 2019 20:57
Show Gist options
  • Save scr34m/935810e5ea422fd0b172 to your computer and use it in GitHub Desktop.
Save scr34m/935810e5ea422fd0b172 to your computer and use it in GitHub Desktop.
raw zeromq wire protocol in php
<?php
// ZMTP/2.0 http://rfc.zeromq.org/spec:15
// ZMTP/1.0 http://rfc.zeromq.org/spec:13
$fp = fsockopen("127.0.0.1", 5559, $errno, $errstr, 1);
if (!$fp) {
return;
}
stream_set_timeout($fp, 0, 500);
$str = str_repeat('abc123', mt_rand(1,100));
$msg = '{"num":'.strlen($str).',"string":"'.$str.'"}';
$length = strlen($msg);
echo $msg . PHP_EOL;
echo $length . PHP_EOL;
// ZMTP/2.0 vs. ZMTP/1.0
if (fread($fp, 1) == 0xff) {
$version = 2;
// server greeting (ff 00 00 00 00 00 00 00 01 7f)
fread($fp, 9);
// client greeting, length, PUSH
$s = pack('CCCCCCCCCCCC', 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x01, 0x08);
fwrite($fp, $s, 12);
// server length, PULL (01, 07)
$s = fread($fp, 2);
// server final short (00 00)
$s = fread($fp, 2);
if ($length < 255) {
fwrite($fp, pack('N', $length), 4);
fwrite($fp, $msg, $length);
} else {
fwrite($fp, pack('CCCNN', 0x00, 0x00, 0x02, 0x00, $length), 1 + 1 + 1 + 4 + 4 + $length);
fwrite($fp, $msg, $length);
}
} else {
$version = 1;
// server greeting (01 00)
fread($fp, 1);
// client greeting
$s = pack('CC', 0x01, 0x00);
fwrite($fp, $s, 2);
if ($length < 255) {
fwrite($fp, pack('CC', $length + 1, 0x00), 2);
fwrite($fp, $msg, $length);
fwrite($fp, pack('C', 0), 1);
} else {
fwrite($fp, pack('CNNC', 0xff, 0x00, $length + 1, 0x00), 1 + 4 + 4 + 1);
fwrite($fp, $msg, $length);
fwrite($fp, pack('C', 0), 1);
}
}
fclose($fp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment