Skip to content

Instantly share code, notes, and snippets.

@brianium
Created March 20, 2012 00:08
Show Gist options
  • Save brianium/2128767 to your computer and use it in GitHub Desktop.
Save brianium/2128767 to your computer and use it in GitHub Desktop.
simple binary socket writer/reader
<?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