\Hazaar\Socket
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.

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();

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();

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();

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; public 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;

Tags

Since

2.0.0

Summary
Methods Properties Constants
get
on
run
set
No constants
Properties
$blocking
$blocking
$connected
$connected
$data
$data
$events
$events
$maxBufferSize
$maxBufferSize
$protocol
$protocol
$select_timeout
$select_timeout
$socket
$socket
Methods
__construct()
__construct($pollInterval = 1000, $protocol = 'sol_tcp')
The \Hazaar\Socket\Client constructor

The class can be instantiated without any arguments and defaults to a TCP socket with 1 second polling interval.

Tags

Throws

Exception\CreateFailed

Parameters

$pollIntervalinteger

The polling interval when used when waiting for data to be received. This affects the frequency by which the onPoll callback is executed.

$protocolinteger

One of SOL_TCP, SOL_UDP or SOL_SOCKET.

close()
close() : boolean
Closes the current socket connection.

Returns

boolean

TRUE if the socket was connected and is now closed. FALSE if the socket was not already connected.

connect()
connect($host, $port) : boolean
Initiates a connection to a remote host.

Parameters

$hoststring

The remote host to connect to specified as either a resolvable host name or an IP address.

$portinteger

The port to connect to on the remote host.

Returns

boolean

TRUE if the connnection is successful. FALSE otherwise.

get()
get($key) : mixed
Return a value previously stored using Client::set()

Parameters

$keystring

The key used to store the value.

Returns

mixed
getLocalIP()
getLocalIP() : string
Get the local IP address of the socket connection

Returns

string
getLocalPort()
getLocalPort() : integer
Get the local port number for the current socket connection.

Returns

integer
getRemoteHost()
getRemoteHost() : string
Returns the remote host address as resolved by the socket connections IP. This can be different to the host name used

to start the connection.

Returns

string
getRemoteIP()
getRemoteIP() : string
Returns the IP address of the remote host.

Returns

string
getRemotePort()
getRemotePort() : integer
Return the port number at the remote end of the current connection.

Returns

integer
isConnected()
isConnected() : boolean
Get the current connection status of the socket.

Returns

boolean

TRUE if the connection is established. FALSE otherwise.

on()
on($event, $callback) : boolean
Register an event handler

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

$eventstring

The name of the event to register the callback on

$callback\Hazaar\Socket\callable

A standard PHP callable. See: http://au2.php.net/manual/en/language.types.callable.php

Returns

boolean
onClose()
onClose()
Built-in callback method used to handle registered event callbacks
onConnect()
onConnect()
Built-in callback method used to handle registered event callbacks
onPoll()
onPoll()
Built-in callback method used to handle registered event callbacks
onRecv()
onRecv($data)
Built-in callback method used to handle registered event callbacks

Parameters

$data

No description

recv()
recv($bytes = null) : string
Receive data from the socket.

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

$bytes

No description

Returns

string
run()
run($timeout = null) : boolean
Run the \Hazaar\Socket\Client main loop.

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

$timeoutinteger

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::$select_timeout value.

Returns

boolean

TRUE if the main loop exited cleanly. FALSE if the socket is not currently connected.

send()
send($data) : mixed
Send data to the remote host

Parameters

$datastring

No description

Returns

mixed

The number of bytes written to the socket. FALSE if an error has occurred.

set()
set($key, $value)
Store a key/value pair in the socket client object.

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

$keystring

The named key to store the value under.

$valuemixed

The value to store. Can be pretty much anything you want.

setBlocking()
setBlocking($state)
Set the socket blocking state.

Parameters

$stateboolean

TRUE will set the socket to blocking mode. FALSE will use non-blocking mode.

setMaxReceiveBuffer()
setMaxReceiveBuffer($bytes)
Set the maximum receive buffer size in bytes.

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

$bytesinteger

The size of the buffer in bytes.

setSelectTimeout()
setSelectTimeout($milliseconds)

Parameters

$milliseconds\Hazaar\Socket\ineteger

Set the timeout used when waiting for data to arrive.

triggerEventQueue()
triggerEventQueue($queue)
Triggers any registered callbacks for the specified event.

Parameters

$queuearray

The event queue of callbacks.

wait()
wait($timeout = null) : boolean
Wait for data to become available for reading on the socket.

This method wraps the standard socket_select() system call using the Client::$select_timeout value. It will block for Client::$select_timeout 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

$timeoutint

If set, specifies the time in milliseconds to wait for data. If not set uses internal select_timeout value.

Returns

boolean

TRUE if data is available. FALSE otherwise.