Created
March 20, 2012 00:08
-
-
Save brianium/2128767 to your computer and use it in GitHub Desktop.
simple binary socket writer/reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Infrastructure\BinarySocket; | |
class BinarySocket | |
{ | |
protected $socket; | |
public function __construct($ip,$port) | |
{ | |
$this->socket = @socket_create(AF_INET,SOCK_STREAM,SOL_TCP); | |
$connected = @socket_connect($this->socket,$ip,$port); | |
if (!$connected) | |
{ | |
require_once 'Exception.php'; | |
throw new BinarySocketException(socket_last_error($this->socket)); | |
} | |
} | |
/** | |
* @param $format the format given to pack() | |
* @param $data the data to write | |
* @param int $length optional length of the buffer | |
*/ | |
public function write($format,$data, $length = 0) | |
{ | |
$binary = call_user_func_array('pack',array_merge(array($format),$data)); | |
socket_write($this->socket,$binary,$length); | |
} | |
public function read($format,$length) | |
{ | |
$buf = ''; | |
$bytes = socket_recv($this->socket,$buf,$length,MSG_WAITALL); | |
if ($bytes === false) | |
{ | |
require_once 'Exception.php'; | |
throw new BinarySocketException(socket_last_error($this->socket)); | |
} | |
return unpack($format,$buf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment