<?phpdefine(
"CONNECTED"
, true);
define(
"DISCONNECTED"
, false); Class Socket {
private
static
$instance
;
private
$connection
= null;
private
$connectionState
= DISCONNECTED;
private
$defaultHost
=
"192.168.128.198"
;
private
$defaultPort
= 9301;
private
$defaultTimeOut
= 60;
public
$debug
= false;
public
function
__construct()
{
}
public
static
function
singleton()
{
if
(self::
$instance
== null || ! self::
$instance
instanceof
Socket)
{ self::
$instance
=
new
Socket();
}
return
self::
$instance
;
}
public
function
connect(
$serverHost
=false,
$serverPort
=false,
$timeOut
=false)
{
if
(
$serverHost
== false)
{
$serverHost
=
$this
->defaultHost;
}
if
(
$serverPort
== false)
{
$serverPort
=
$this
->defaultPort;
}
$this
->defaultHost =
$serverHost
;
$this
->defaultPort =
$serverPort
;
if
(
$timeOut
== false)
{
$timeOut
=
$this
->defaultTimeOut;
}
$this
->connection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if
(socket_connect(
$this
->connection,
$serverHost
,
$serverPort
) == false)
{
$errorString
= socket_strerror(socket_last_error(
$this
->connection));
$this
->_throwError(
"Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}"
);
}
else
{
$this
->_throwMsg(
"Socket connected!"
);
}
$this
->connectionState = CONNECTED;
}
public
function
disconnect()
{
if
(
$this
->validateConnection())
{
socket_close(
$this
->connection);
$this
->connectionState = DISCONNECTED;
$this
->_throwMsg(
"Socket disconnected!"
);
return
true;
}
return
false;
}
public
function
sendRequest(
$data
)
{
if
(
$this
->validateConnection())
{
$result
= socket_write(
$this
->connection,
$data
,
strlen
(
$data
));
return
$result
;
}
else
{
$this
->_throwError(
"Sending command \"{$data}\" failed.<br>Reason: Not connected"
);
}
}
public
function
getResponse()
{
if
(
$this
->validateConnection())
{
if
( (
$ret
= socket_read(
$this
->connection,8192)) == false){
$this
->_throwError(
"Receiving response from server failed.<br>Reason: Not bytes to read"
);
return
false;
}
else
{
return
$ret
;
}
}
}
public
function
isConn()
{
return
$this
->connectionState;
}
public
function
getUnreadBytes()
{
$info
= socket_get_status(
$this
->connection);
return
$info
['unread_bytes'];
}
public
function
getConnName(&
$addr
, &
$port
)
{
if
(
$this
->validateConnection())
{
socket_getsockname(
$this
->connection,
$addr
,
$port
);
}
}
public
function
waitForResponse()
{
if
(
$this
->validateConnection())
{
return
socket_read(
$this
->connection, 2048);
}
$this
->_throwError(
"Receiving response from server failed.<br>Reason: Not connected"
);
return
false;
}
private
function
validateConnection()
{
return
(
is_resource
(
$this
->connection) && (
$this
->connectionState != DISCONNECTED));
}
private
function
_throwError(
$errorMessage
)
{
echo
"Socket error: "
.
$errorMessage
;
}
private
function
_throwMsg(
$msg
)
{
if
(
$this
->debug)
{
echo
"Socket message: "
.
$msg
.
"\n\n"
;
}
}
public
function
__destruct()
{
$this
->disconnect();
}
}