Skip to content

Instantly share code, notes, and snippets.

@rafaelcanovas
Created May 11, 2012 18:20
Show Gist options
  • Save rafaelcanovas/2661490 to your computer and use it in GitHub Desktop.
Save rafaelcanovas/2661490 to your computer and use it in GitHub Desktop.
<?php
/**
* Copyright (C) 2012 Rafael Canovas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
class NetworkMessage
{
private $buffer = '';
private $readPos = 0;
public function __construct($buffer = '') {
$this->buffer = $buffer;
}
public function getReadPos() {return $this->readPos;}
public function getLength() {return strlen($this->buffer);}
public function putByte($v)
{
$this->buffer .= pack('C', $v);
}
public function putU16($v)
{
$this->buffer .= pack('v', $v);
}
public function putU32($v)
{
$this->buffer .= pack('V', $v);
}
public function putString($s)
{
$this->putU16(strlen($s));
$this->buffer .= $s;
}
public function getByte()
{
$v = unpack('C', $this->buffer[$this->readPos]);
$this->readPos++;
return $v[1];
}
public function getU16()
{
$v = unpack('v', substr($this->buffer, $this->readPos, 2));
$this->readPos += 2;
return $v[1];
}
public function getU32()
{
$v = unpack('V', substr($this->buffer, $this->readPos, 4));
$this->readPos += 4;
return $v[1];
}
public function getString($length = false)
{
if($length === false) {
$length = $this->getU16();
}
$v = substr($this->buffer, $this->readPos, $length);
$this->readPos += $length;
return $v;
}
public function skipBytes($count)
{
$this->readPos += $count;
}
public function __toString() {
// Prepare a real packet for output
return pack('v', strlen($this->buffer)) . $this->buffer;
}
}
class NetworkMessageIterator implements Iterator
{
public function __construct(NetworkMessage &$msg)
{
$this->msg = $msg;
}
function current() {}
function key() {}
function next() {}
function rewind() {}
function valid() {
return $this->msg->getReadPos() < $this->msg->getLength();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment