Client
Client
The socket client class.
The socket client class is used to establish connections via TCP or send data via UDP sockets to another host. It can be implemented as a stand-alone class object and used to send or receive data by polling. It can also be extended and use event handler methods that are triggered when a connection is established, data is received, etc. It's also possible to register event callback methods on the stand-alone object to allow for maximum flexibility in how the class can be used.
h3. Example #1 - Standalone Object:
This example creates the client as a standalone object. It requests a connection and then once connected we send some data to the remote server. After that we wait for $pollInterval milliseconds (default 1000) for data to arrive before dumping it to the output buffer and closing the connection.
//Create the socket client object
$client = new \Hazaar\Socket\Client();
//Connect to the remote host
$client->connect('www.google.com.au', 80) or die('Connection failed!');
//Send some data
$client->send("GET /\n");
//Waits for $pollInterval milliseconds for data to arrive
if ($client->wait()) {
var_dump($client->recv());
}
//Close the connection
$client->close();
exit();
h3. Example #2 - Standalone object using callbacks (simple):
This example does the same thing as example #1 but using callback methods.
//Create the socket client object
$client = new \Hazaar\Socket\Client();
//Register a connect callback. This call back will send some data when it's triggered.
$client->on('connect', function($client){
$client->send("GET /\n");
});
//Register a receive data callback. This call back will dump out the received data and then close the connection.
$client->on('recv', function($client, $data){
var_dump($data);
$client->close();
});
//Connect to the remote host
$client->connect('www.google.com.au', 80) or die('Connection failed!');
//Run the socket client for 5 seconds.
$client->run(5);
exit();
h3. Example #3 - Standalone object using callbacks (advanced):
This example does the same thing as example #2 except instead of just running the client for 5 seconds until data arrives, we register a poll event handler to implement our own timeout code.
//Create the socket client object
$client = new \Hazaar\Socket\Client();
//Register a connect callback. This call back will send some data when it's triggered.
$client->on('connect', function($client){
$client->set('start', time());
$client->send("GET /\n");
});
//Register a receive data callback. This call back will dump out the received data
//and then close the connection.
$client->on('recv', function($client, $data){
var_dump($data);
$client->close();
});
//Register a poll callback. This is triggered each time the main run() loop cycles.
//Here we wait 5 seconds before returning false to tell the main loop to exit.
$client->on('poll', function($client){
if((time() - $client->get('start')) >= 5 )
return false;
});
//Connect to the remote host
$client->connect('www.google.com.au', 80) or die('Connection failed!');
//Run the socket client indefinitely.
$client->run();
exit();
h3. Example #4 - Class extension:
This example creates the client as a sub-class of \Hazaar\Socket\Client. This allows you to override the default event handlers and execute your code within the context of the sub-class.
class MyGoogleClient extends \Hazaar\Socket\Client {
private $start;
private $timeout = 5;
function __construct() {
parent::__construct();
$this->connect('www.google.com.au', 80) or die('Connection failed!');
$this->run();
}
protected function onConnect() {
echo "Connected to Google!\n";
$this->set('start', time());
$this->send("GET /\n");
}
protected function onRecv($data) {
var_dump($data);
$this->close();
}
protected function onPoll() {
if ((time() - $this->start) >= $this->timeout)
return false;
}
}
$client = new MyGoogleClient();
exit;
Properties
protocol
private int $protocol
public $
maxBufferSize
private int $maxBufferSize
selectTimeout
private int $selectTimeout
blocking
private bool $blocking
connected
private bool $connected
events
private array $events
data
private array $data
Methods
__construct
The \Hazaar\Socket\Client constructor.
public __construct({Array})
The class can be instantiated without any arguments and defaults to a TCP socket with 1 second polling interval.
Parameters
Parameter | Type | Description |
---|---|---|
$selectTimeout | int | |
$protocol | int | one of SOL_TCP, SOL_UDP or SOL_SOCKET |
setBlocking
Set the socket blocking state.
public setBlocking({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$state | bool | TRUE will set the socket to blocking mode. FALSE will use non-blocking mode. |
setMaxReceiveBuffer
Set the maximum receive buffer size in bytes.
public setMaxReceiveBuffer({Array})
This is the size of the buffer used to retrieve data from the socket. If the buffer is smaller than the amount of data waiting to be retrieved then multiple calls to recv() will be required.
Parameters
Parameter | Type | Description |
---|---|---|
$bytes | int | the size of the buffer in bytes |
setSelectTimeout
public setSelectTimeout({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$milliseconds | int | set the timeout used when waiting for data to arrive |
getRemoteHost
Returns the remote host address as resolved by the socket connections IP. This can be different to the host name used
public getRemoteHost({Array})
to start the connection.
getRemoteIP
Returns the IP address of the remote host.
public getRemoteIP({Array})
getRemotePort
Return the port number at the remote end of the current connection.
public getRemotePort({Array})
getLocalIP
Get the local IP address of the socket connection.
public getLocalIP({Array})
getLocalPort
Get the local port number for the current socket connection.
public getLocalPort({Array})
connect
Initiates a connection to a remote host.
public connect({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$host | string | the remote host to connect to specified as either a resolvable host name or an IP address |
$port | string | the port to connect to on the remote host |
close
Closes the current socket connection.
public close({Array})
isConnected
Get the current connection status of the socket.
public isConnected({Array})
set
Store a key/value pair in the socket client object.
public set({Array})
This is useful if you are using Closures as callback methods. Using a Closure will stomp the scope where the Closure is defined meaning you won't have access to variables defined outside of the Closure. This allows data to be stored in the current client object that can then be accessed later from any other callback method, or from anywhere that has access to the client object.
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | the named key to store the value under |
$value | mixed | The value to store. Can be pretty much anything you want. |
get
Return a value previously stored using Client::set().
public get({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | the key used to store the value |
on
Register an event handler.
public on({Array})
This method is used to register an event that will be called when an event is triggered.
Valid event names are:
- connect - Called when a socket connection is successfully established
- recv - Called when data is received
- close - Called when the socket connection is closed.
- poll - Called when using the Client::run() method to wait for data.
Parameters
Parameter | Type | Description |
---|---|---|
$event | string | The name of the event to register the callback on |
$callback | \Closure | A standard PHP callable. See: http://au2.php.net/manual/en/language.types.callable.php |
send
Send data to the remote host.
public send({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$data | string |
recv
Receive data from the socket.
public recv({Array})
This method will return up to Client::$maxBufferSize bytes of data received on the socket from the remote host.
This call will block if blocking mode is enabled. See: Client::setBlocking()
Parameters
Parameter | Type | Description |
---|---|---|
$bytes | int |
wait
Wait for data to become available for reading on the socket.
public wait({Array})
This method wraps the standard socket_select() system call using the Client::$selectTimeout value. It will block for Client::$selectTimeout milliseconds or until data is available for reading on the socket. If blocking mode is enabled however, it will wait indefinitely for data to be available.
Parameters
Parameter | Type | Description |
---|---|---|
$timeout | int | If set, specifies the time in milliseconds to wait for data. If not set uses internal selectTimeout value. |
run
Run the \Hazaar\Socket\Client main loop.
public run({Array})
Calling this method causes the socket client to execute as though it was it's own application. By default it will return only once the socket connection is closed, or an onPoll() callback returns false to indicate the main loop should exit (after which a Client::close() should be called separately).
An optional timeout can be specified here as will. This will cause the client 'application' to run, but only for $timeout seconds, allowing a short run process to send and receive a single response easily without hanging the system.
Parameters
Parameter | Type | Description |
---|---|---|
$timeout | int | How long to run the main loop for. This may not end up being exact as it is influenced by execution time |
of any callbacks as well as the Client::$selectTimeout value. |
onConnect
Built-in callback method used to handle registered event callbacks.
protected onConnect({Array})
onRecv
Built-in callback method used to handle registered event callbacks.
protected onRecv({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$data | string |
onClose
Built-in callback method used to handle registered event callbacks.
protected onClose({Array})
onPoll
Built-in callback method used to handle registered event callbacks.
protected onPoll({Array})
triggerEventQueue
Triggers any registered callbacks for the specified event.
private triggerEventQueue({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$queue | array | the event queue of callbacks |
Generated by Hazaar API Doc Generator