Socket Class

A quick example of a socket class for connecting to a server in PHP and communicating data.

class Client {

// $host - IP of server to connect to.
// $port - Port of server to connect to.
function __construct($host,$port)
{
if(!$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))
{
die('ERROR: ' . socket_strerror(socket_last_error()) . '\n');
}
$host = GetHostByName($host);
if(!socket_connect($this->sock, $host, $port)) {
die("ERROR: " . socket_strerror(socket_last_error()) . "\n");
}
// Blocking sockets
// Optional. Will pause the script if no data
// has been received on socket until there is data.
socket_set_block($this->sock);
echo 'Connected';
switch(socket_select($r = array($this->sock), $w = array($this->sock), $f = array($this->sock), 5))
{
case 2:
echo "[-] Connection Refused\n"; flush();
$fail = true;
break;
case 1:
echo "[+] Connected\n"; flush();
$fail = false;
break;
case 0:
echo "[-] Timeout\n"; flush();
$fail = true;
break;
}
if(!$fail)
{
return true;
}
else
{
return false;
}
}

function data_read()
{
if($read=socket_read($this->sock,512,PHP_NORMAL_READ))
{
// Remove carriage return and end line tags from data
$read = str_replace(array("\n","\r"),array('',''), $read);
echo "[SOCKET] (Read) ".$read."\n";
return $read;
}
else
{
echo "No Data From Socket: ".socket_strerror(socket_last_error())."\nDisconnecting and Shutting Down.\n"; $this->disconnect_sock();
exit(0);
}
}

function data_send($buffer)
{
if((strlen($buffer)>0) && (strlen($buffer)<=512))
{
// Append carriage return and end line tags to buffer
$buffer .= "\r\n";
$write = socket_write($this->sock, $buffer, strlen($buffer));
echo "[SOCKET] (Write) $buffer\n";
}
}

}