[TASK] Moved the project to namespaces.
[TASK] Removed all the protocol handlers. [TASK] Clients are no longer part of the SocketFramework itself. [TASK] The Framework provides an "interface" to external clients - the ClientDispatcher. [TASK] Added the Core package and added a better ClassLoader. [TASK] Created a bootstrap module to include in other projects. [TASK] Cleaned up comments, reformatted them.
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
/**
|
||||
* This file bootstraps the SocketFramework by initializing the error_reporting to E_ALL
|
||||
* and initializing the ClassLoader.
|
||||
* @author jpt
|
||||
*/
|
||||
error_reporting(\E_ALL);
|
||||
require_once("Classes" . \DIRECTORY_SEPARATOR . "Core" . \DIRECTORY_SEPARATOR . "ClassLoader.php");
|
||||
|
||||
$classLoader = new \JPT\SocketFramework\Core\ClassLoader();
|
||||
$classLoader->initialize();
|
||||
?>
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Client;
|
||||
|
||||
/**
|
||||
* Abstract class that implements the basic api for the client dispatcher.
|
||||
* If you want to write your own client dispatcher (which should be very normal),
|
||||
* you have to extend this class, so you're able to use it in this socket framework.
|
||||
*
|
||||
* @author jpt
|
||||
* @abstract
|
||||
* @package Client
|
||||
*/
|
||||
abstract class AbstractClientDispatcher implements \JPT\SocketFramework\Client\ClientDispatcherInterface {
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $ID;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $group;
|
||||
|
||||
/**
|
||||
* Contains a reference to the ClientManager in order to change stuff on the fly.
|
||||
*
|
||||
* @var \JPT\SocketFramework\Client\ClientManager
|
||||
*/
|
||||
protected $clientManager;
|
||||
|
||||
/**
|
||||
* Forwards incoming data to the ProtocolHandler
|
||||
* Let's the ProtocolHandler do all the work and forward its results to the Clients.
|
||||
* Return resulting raw data.
|
||||
*
|
||||
* @param string $rawData
|
||||
* @return string
|
||||
*/
|
||||
public function processRawData($rawData) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will load the given config.
|
||||
*
|
||||
* @param array $config
|
||||
* @return void
|
||||
*/
|
||||
abstract public function loadConfig($config);
|
||||
|
||||
/**
|
||||
* Will reset the connectionStatus of the client.
|
||||
* Implementation is optional and depends on the client.
|
||||
* Should be used to reset internal variables.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function resetConnectionStatus() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This function gets called every time, the connection is established.
|
||||
* This allows the client to send initial data.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initializeConnection() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the ID.
|
||||
*
|
||||
* @param int $id
|
||||
* @return void
|
||||
*/
|
||||
public function setID($id) {
|
||||
$this->ID = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the group.
|
||||
*
|
||||
* @param string $group
|
||||
* @return void
|
||||
*/
|
||||
public function setGroup($group) {
|
||||
$this->group = $group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects ClientManager
|
||||
*
|
||||
* @param \JPT\SocketFramework\Client\ClientManager $clientManager
|
||||
* @return void
|
||||
* @throws \JPT\SocketFramework\Exception\WrongDatatypeException
|
||||
*/
|
||||
public function injectClientManager($clientManager) {
|
||||
if(!$clientManager instanceof \JPT\SocketFramework\Client\ClientManager) {
|
||||
throw new Exception_WrongDatatypeException("Cannot inject ClientManager! Expected an instance of \JPT\SocketFramework\Client\ClientManager, '" . get_type($clientManager) . "' given.", 1291156565);
|
||||
}
|
||||
$this->clientManager = $clientManager;
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Client;
|
||||
|
||||
/**
|
||||
* Interface that includes the real must-have stuff.
|
||||
*
|
||||
* @author jpt
|
||||
* @interface
|
||||
* @package Client
|
||||
*/
|
||||
interface ClientDispatcherInterface {
|
||||
|
||||
/**
|
||||
* Forwards incoming data to the ProtocolHandler
|
||||
* Let's the ProtocolHandler do all the work and forward its results to the Clients.
|
||||
* Return resulting raw data.
|
||||
*
|
||||
* @param string $rawData
|
||||
* @return string
|
||||
*/
|
||||
public function processRawData($rawData);
|
||||
|
||||
/**
|
||||
* This function will load the given config.
|
||||
*
|
||||
* @param array $config
|
||||
* @return void
|
||||
*/
|
||||
abstract public function loadConfig($config);
|
||||
|
||||
/**
|
||||
* Will reset the connectionStatus of the client.
|
||||
* Implementation is optional and depends on the client.
|
||||
* Should be used to reset internal variables.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function resetConnectionStatus();
|
||||
|
||||
/**
|
||||
* This function gets called every time, the connection is established.
|
||||
* This allows the client to send initial data.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function initializeConnection();
|
||||
|
||||
/**
|
||||
* Sets the ID.
|
||||
*
|
||||
* @param int $id
|
||||
* @return void
|
||||
*/
|
||||
public function setID($id);
|
||||
|
||||
/**
|
||||
* Sets the group.
|
||||
*
|
||||
* @param string $group
|
||||
* @return void
|
||||
*/
|
||||
public function setGroup($group);
|
||||
|
||||
/**
|
||||
* Injects ClientManager.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Client\ClientManager $clientManager
|
||||
* @return void
|
||||
* @throws \JPT\SocketFramework\Exception\WrongDatatypeException
|
||||
*/
|
||||
public function injectClientManager($clientManager);
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,344 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Client;
|
||||
|
||||
/**
|
||||
* This class contains the connection handler.
|
||||
* It handles all the incoming and outgoing data by forwarding it
|
||||
* to the clients for the specific connection.
|
||||
*
|
||||
* @author jpt
|
||||
* @package Client
|
||||
* @depends Connection
|
||||
*/
|
||||
class ClientManager {
|
||||
|
||||
/**
|
||||
* @var \JPT\SocketFramework\Connection\ConnectionPool
|
||||
*/
|
||||
protected $connectionPool;
|
||||
|
||||
/**
|
||||
* An array that contains all client instances for each connection.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $clientDispatcherPool;
|
||||
|
||||
/**
|
||||
* An array that contains all client dispatchers we have for certain "protocols".
|
||||
* How it works: Each independent client dispatcher is assigned a - hopefully unique -
|
||||
* identifier for the protocol it implements.
|
||||
* e.g. ["MyAwesomeIrcClientStuff"] -> $classNameOfMyClientDispatcher
|
||||
* This way, we can register any client dispatcher from even seperate projects,
|
||||
* so we can use them within this framework.
|
||||
*
|
||||
* Ah, maybe this is important to understand it:
|
||||
* The protocol identifier pointing to the class name of the client dispatcher
|
||||
* is used to bind the client dispatcher to a connection created.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $registeredClientDispatchers;
|
||||
|
||||
/**
|
||||
* Contains Connection-attached configurations.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $configPool;
|
||||
|
||||
|
||||
/**
|
||||
* Default constructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->connectionPool = new \JPT\SocketFramework\Connection\ConnectionPool();
|
||||
$this->clientDispatcherPool = array();
|
||||
$this->registeredProtocols = array();
|
||||
$this->configPool = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Default destructor. Closes connections before being killed.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __destruct() {
|
||||
unset($this->clientDispatcherPool);
|
||||
unset($this->connectionPool);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see Connection_ConnectionPool
|
||||
* @return int
|
||||
*/
|
||||
public function countSockets() {
|
||||
return $this->connectionPool->countSockets();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the amount of connected connection handlers.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Connection\ConnectionPool
|
||||
* @return int
|
||||
*/
|
||||
public function countActiveConnections() {
|
||||
return $this->connectionPool->countActiveConnections();
|
||||
}
|
||||
|
||||
/**
|
||||
* Main worker procedure.
|
||||
* Processes incoming data, calls clients and much more.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function work() {
|
||||
//first, create clients for connections that do NOT have one already.
|
||||
foreach($this->connectionPool->getConnectionHandlers() AS $connectionHandler) {
|
||||
if(isset($this->clientDispatcherPool[$connectionHandler->getID()])) continue;
|
||||
//new connections might need a client, so we'll create one here.
|
||||
$this->addClientForConnectionHandler($connectionHandler);
|
||||
//allow client to send initial stuff right after connecting to the server.
|
||||
$this->initializeClientForConnectionHandler($connectionHandler);
|
||||
}
|
||||
|
||||
//then, process all connections that have stuff to read.
|
||||
$connectionHandlers = $this->connectionPool->select();
|
||||
//nothing to do? return right now. :)
|
||||
if(isset($connectionHandlers["read"]) === FALSE || count($connectionHandlers["read"]) === 0) return;
|
||||
foreach($connectionHandlers["read"] AS $connectionHandler) {
|
||||
//handle disconnects
|
||||
if($connectionHandler->isConnected() === FALSE && $connectionHandler->isListening() === FALSE) {
|
||||
//do we need to reconnect? do it.
|
||||
if($connectionHandler->getReconnect() === TRUE) $this->handleReconnectForConnectionHandler($connectionHandler);
|
||||
//this old connectionHandler won't do much anymore - kill it.
|
||||
$this->removeClientForConnectionHandler($connectionHandler);
|
||||
//since the old connectionHandler does not exist anymore, continue.
|
||||
continue;
|
||||
}
|
||||
//handle accepted sockets, adopt them and treat them with care :-)
|
||||
if($connectionHandler->isListening() === TRUE) {
|
||||
$this->addClientForConnectionHandler($connectionHandler);
|
||||
$this->initializeClientForConnectionHandler($connectionHandler);
|
||||
}
|
||||
|
||||
//prepare and get input
|
||||
$incomingData = "";
|
||||
$outgoingData = "";
|
||||
while($data = $connectionHandler->read()) $incomingData .= $data;
|
||||
unset($data);
|
||||
|
||||
//call the registered client
|
||||
if(isset($this->clientDispatcherPool[$connectionHandler->getID()])) $outgoingData .= $this->clientDispatcherPool[$connectionHandler->getID()]->processRawData($incomingData);
|
||||
|
||||
//i don't know what to do here... maybe call a connection bridge?
|
||||
|
||||
//output will be sent.
|
||||
if($outgoingData !== "") $connectionHandler->write($outgoingData);
|
||||
}
|
||||
//after that, we're done here.
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls ConnectionPool in order to create a simple connection.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Connection\ConnectionPool
|
||||
* @param string $group
|
||||
* @param boolean $IPv6
|
||||
* @return \JPT\SocketFramework\Connection\ConnectionHandler
|
||||
*/
|
||||
public function createTcpConnection($group = "", $protocol = "RAW", $IPv6 = FALSE) {
|
||||
return $this->connectionPool->createTcpConnection($group, $protocol, $IPv6);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes and removes the connection.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $connectionHandler
|
||||
* @return void
|
||||
*/
|
||||
public function removeConnection($connectionHandler) {
|
||||
unset($this->configPool[$connectionHandler->getID()]);
|
||||
unset($this->clientDispatcherPool[$connectionHandler->getID()]);
|
||||
$this->connectionPool->removeConnectionHandler($connectionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a protocol identifier and its specific client dispatcher.
|
||||
*
|
||||
* @param string $protocolIdentifier
|
||||
* @param string $className
|
||||
* @return void
|
||||
*/
|
||||
public function registerClientDispatcherByProtocol($protocolIdentifier, $className) {
|
||||
$this->registeredClientDispatchers[$protocolIdentifier] = $className;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters a client dispatcher by its protocol identifier.
|
||||
*
|
||||
* @param string $protocol
|
||||
* @return void
|
||||
*/
|
||||
public function unregisterClientDispatcherByProtocol($protocolIdentifier) {
|
||||
unset($this->registeredClientDispatchers[$protocolIdentifier]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a configuration to a connection.
|
||||
* Will overwrite the existing configuration for the connection.
|
||||
*
|
||||
* @param array $config
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $connectionHandler
|
||||
* @return void
|
||||
*/
|
||||
public function attachConfig($config, $connectionHandler) {
|
||||
$this->configPool[$connectionHandler->getID()] = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls ConnectionPool.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Connection\ConnectionPool
|
||||
* @param int $id
|
||||
* @param string $data
|
||||
* @return void
|
||||
*/
|
||||
public function sendToID($id, $data) {
|
||||
return $this->connectionPool->writeToID($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of available connection IDs.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getIDs() {
|
||||
$list = array();
|
||||
foreach($this->connectionPool->getConnectionHandlers() AS $connectionHandler) $list[] = $connectionHandler->getID();
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of available connection groups.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getGroups() {
|
||||
$list = array();
|
||||
foreach($this->connectionPool->getConnectionHandlers() AS $connectionHandler) $list[] = $connectionHandler->getGroup();
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls Connection_Pool.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Connection\ConnectionPool
|
||||
* @param string $group
|
||||
* @param string $data
|
||||
* @return void
|
||||
*/
|
||||
public function sendToGroup($group, $data) {
|
||||
return $this->connectionPool->writeToGroup($group, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the registered client dispatcher for the given protocol.
|
||||
* Returns a client dispatcher instance or void.
|
||||
*
|
||||
* @param string $protocol
|
||||
* @return mixed
|
||||
* @throws \JPT\SocketFramework\Exception\GeneralException
|
||||
*/
|
||||
protected function createClientDispatcherForProtocol($protocolIdentifier) {
|
||||
//look for the protocol
|
||||
if(!in_array($protocolIdentifier, $this->registeredClientDispatchers)) {
|
||||
throw new \JPT\SocketFramework\Exception\GeneralException("No client dispatcher is registered for protocol: '" . $protocol . "'!", 1290271651);
|
||||
}
|
||||
$className = $this->registeredClientDispatchers[$protocolIdentifier];
|
||||
//look for the class
|
||||
if(class_exists($className)) {
|
||||
//TODO: This looks ugly and wrong. Ideas, anyone?
|
||||
$clientDispatcher = new $className();
|
||||
if(!$clientDispatcher instanceof \JPT\SocketFramework\Client\AbstractClientDispatcher) throw new \JPT\SocketFramework\Exception\GeneralException("Class '" . $className . "' does not implement the AbstractClientDispatcher-API!", 1294837055);
|
||||
return $clientDispatcher;
|
||||
} else {
|
||||
throw new \JPT\SocketFramework\Exception\GeneralException("Registered class name '" . $className . "' does not exist for protocol: '" . $protocol . "'!", 1290271773);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the client dispatcher of a given connectionHandler.
|
||||
* This should be done after establishing a connection.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $connectionHandler
|
||||
* @return void
|
||||
*/
|
||||
protected function initializeClientForConnectionHandler($connectionHandler) {
|
||||
$this->clientDispatcherPool[$connectionHandler->getID()]->initializeConnection();
|
||||
//after initializing, have it process an empty string in order to get stuff to write. >.<
|
||||
$result = $this->clientDispatcherPool[$connectionHandler->getID()]->processRawData("");
|
||||
if($result !== "") $connectionHandler->write($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new connectionHandler, resets the client dispatchers connection status,
|
||||
* copies the old config and assigns the new connectionHandler to the clientdispatcher.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $connectionHandler
|
||||
* @return void
|
||||
*/
|
||||
protected function handleReconnectForConnectionHandler($connectionHandler) {
|
||||
//have the connectionHandler do the reconnect.
|
||||
$newConnectionHandler = $connectionHandler->reconnect();
|
||||
//get the client and reset it.
|
||||
$client = $this->clientDispatcherPool[$connectionHandler->getID()];
|
||||
$client->resetConnectionStatus();
|
||||
//assign the client to the new connectionHandler.
|
||||
$this->clientDispatcherPool[$newConnectionHandler->getID()] = $client;
|
||||
//get the config and assign it to the new connectionHandler, too.
|
||||
$config = $this->configPool[$connectionHandler->getID()];
|
||||
$this->configPool[$newConnectionHandler->getID()] = $config;
|
||||
//re-initialize the client
|
||||
$this->initializeClientForConnectionHandler($newConnectionHandler);
|
||||
//remove old connection
|
||||
$this->removeConnection($connectionHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a client dispatcher to our client dispatcher pool.
|
||||
* The "RAW" protocol identifier is used to not create a client.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $connectionHandler
|
||||
* @return void
|
||||
*/
|
||||
protected function addClientDispatcherForConnectionHandler($connectionHandler) {
|
||||
$protocolIdentifier = $this->registeredProtocols[$connectionHandler->getProtocol()];
|
||||
//do not try this for "RAW" connections - might or might not be useful.
|
||||
if($protocolIdentifier === "RAW") return;
|
||||
$clientDispatcher = $this->createClientDispatcherForProtocol($protocolIdentifier);
|
||||
if(isset($this->configPool[$connectionHandler->getID()])) {
|
||||
$clientDispatcher->loadConfig($this->configPool[$connectionHandler->getID()]);
|
||||
}
|
||||
$clientDispatcher->injectClientManager($this);
|
||||
$clientDispatcher->setID($connectionHandler->getID());
|
||||
$clientDispatcher->setGroup($connectionHandler->getGroup());
|
||||
$this->clientDispatcherPool[$connectionHandler->getID()] = $clientDispatcher;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a client dispatcher from our client dispatcher pool.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $connectionHandler
|
||||
* @return void
|
||||
* @throws \JPT\SocketFramework\Exception\WrongDatatypeException
|
||||
*/
|
||||
protected function removeClientForConnectionHandler($connectionHandler) {
|
||||
unset($this->clientDispatcherPool[$connectionHandler->getID()]);
|
||||
$this->connectionPool->removeConnectionHandler($connectionHandler);
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,447 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Connection;
|
||||
|
||||
/**
|
||||
* This class is a decorator for the SocketHandler class.
|
||||
* It provides a buffer for the SocketHandler, so reading and writing
|
||||
* a full line won't be that much pain.
|
||||
*
|
||||
* @author jpt
|
||||
* @package Connection
|
||||
* @depends Socket
|
||||
* @depends Misc
|
||||
*/
|
||||
class ConnectionHandler {
|
||||
|
||||
/**
|
||||
* Buffer that contains incoming data.
|
||||
* Contents were received from the SocketHandler.
|
||||
* This buffer does not use a linebreak, it's a temporary store for data.
|
||||
*
|
||||
* @var \JPT\SocketFramework\Misc\Buffer
|
||||
*/
|
||||
protected $bufferIncoming;
|
||||
|
||||
/**
|
||||
* Buffer that contains outgoing data.
|
||||
* Contents will be sent to the SocketHandler.
|
||||
* This buffer does not use a linebreak, it's a temporary store for data.
|
||||
*
|
||||
* @var \JPT\SocketFramework\Misc\Buffer
|
||||
*/
|
||||
protected $bufferOutgoing;
|
||||
|
||||
/**
|
||||
* Contains the instance of the SocketHandler class.
|
||||
* According to the Liskov substitution principle, decoration pattern must be used in this case.
|
||||
*
|
||||
* @var \JPT\SocketFramework\Socket\SocketHandler
|
||||
*/
|
||||
protected $socketHandler;
|
||||
|
||||
/**
|
||||
* @var \JPT\SocketFramework\Connection\ConnectionPool
|
||||
*/
|
||||
protected $connectionPool;
|
||||
|
||||
/**
|
||||
* A boolean that indicates whether this Connection is a listening server socket or a usual client socket.
|
||||
*
|
||||
* @var boolean
|
||||
*/
|
||||
protected $isServer;
|
||||
|
||||
/**
|
||||
* Unique Connection ID.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $id;
|
||||
|
||||
/**
|
||||
* Connection Group.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $group;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $protocol;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $IPv6;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $host;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $port;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $reconnectOnDisconnect;
|
||||
|
||||
/**
|
||||
* Calls parent constructor.
|
||||
*
|
||||
* @param $socket
|
||||
* @param $linebreak
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($socket, $id, $group = "", $protocol = "") {
|
||||
$this->bufferIncoming = new \JPT\SocketFramework\Misc\Buffer();
|
||||
$this->bufferOutgoing = new \JPT\SocketFramework\Misc\Buffer();
|
||||
$this->socketHandler = new \JPT\SocketFramework\Socket\SocketHandler($socket);
|
||||
$this->id = $id;
|
||||
$this->group = $group;
|
||||
$this->protocol = $protocol;
|
||||
$this->isServer = FALSE;
|
||||
$this->host = "";
|
||||
$this->port = 0;
|
||||
$this->reconnectOnDisconnect = FALSE;
|
||||
$this->IPv6 = FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls parent destructor.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __destruct() {
|
||||
unset($this->socketHandler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Injector for the internal ConnectionPool access.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionPool $connectionPool
|
||||
* @return void
|
||||
*/
|
||||
public function injectConnectionPool($connectionPool) {
|
||||
$this->connectionPool = $connectionPool;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getProtocol() {
|
||||
return $this->protocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Connection Group
|
||||
*/
|
||||
public function getGroup() {
|
||||
return $this->group;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int Connection ID
|
||||
*/
|
||||
public function getID() {
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether this connection is a listening socket or a general client connection socket.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function isServer() {
|
||||
return $this->isServer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the IPv6-flag.
|
||||
*
|
||||
* @param boolean $IPv6
|
||||
* @return void
|
||||
*/
|
||||
public function setIPv6($IPv6) {
|
||||
$this->IPv6 = $IPv6;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets reconnectOnDisconnect flag.
|
||||
*
|
||||
* @param boolean $reconnect
|
||||
* @return void
|
||||
*/
|
||||
public function setReconnect($reconnect) {
|
||||
$this->reconnectOnDisconnect = $reconnect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets reconnectOnDisconnect flag.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function getReconnect() {
|
||||
return $this->reconnectOnDisconnect;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function is called when socket_read() or socket_write() fail.
|
||||
* It creates a new ConnectionHandler that will reconnect.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function shutdown() {
|
||||
$this->setConnected(FALSE);
|
||||
$this->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads from SocketHandler, writes into bufferIncoming.
|
||||
* Returns a boolean that will indicate whether the socket is still okay.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return boolean
|
||||
*/
|
||||
public function readToBuffer() {
|
||||
$data = $this->socketHandler->read();
|
||||
//set connection status flag properly.
|
||||
if($data === "") {
|
||||
$this->shutdown();
|
||||
return FALSE;
|
||||
}
|
||||
$this->bufferIncoming->addData($data);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the bufferOutgoing to the SocketHandler.
|
||||
* Returns a boolean that will indicate whether the socket is still okay.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return boolean
|
||||
*/
|
||||
public function writeFromBuffer() {
|
||||
$bufferContent = $this->bufferOutgoing->getAllBufferContents();
|
||||
//this might not be cool, but it should do.
|
||||
if($bufferContent === "") return TRUE;
|
||||
$result = $this->socketHandler->write($bufferContent);
|
||||
if($result === FALSE) {
|
||||
$this->shutdown();
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls error() on \JPT\SocketFramework\Socket\SocketHandler.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function handleSocketError() {
|
||||
$this->socketHandler->error();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether this ConnectionHandler has data to read.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function canRead() {
|
||||
return $this->bufferIncoming->hasData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether this ConnectionHandler has data to write.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function canWrite() {
|
||||
return $this->bufferOutgoing->hasData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads new data into bufferIncoming.
|
||||
* Returns a full line from bufferIncoming.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function read() {
|
||||
return $this->bufferIncoming->getAllBufferContents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes data into bufferOutgoing.
|
||||
* Sends data from bufferOutgoing to the SocketHandler.
|
||||
*
|
||||
* @param $data
|
||||
* @return void
|
||||
*/
|
||||
public function write($data) {
|
||||
$this->bufferOutgoing->addData($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return ressource
|
||||
*/
|
||||
public function accept() {
|
||||
return $this->socketHandler->accept();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return string
|
||||
*/
|
||||
public function getRemoteName() {
|
||||
return $this->socketHandler->getRemoteName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return string
|
||||
*/
|
||||
public function getLocalName() {
|
||||
return $this->socketHandler->getLocalName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function close() {
|
||||
return $this->socketHandler->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler, stores connection data.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param string $address
|
||||
* @param int $port
|
||||
* @return void
|
||||
*/
|
||||
public function connect($address, $port) {
|
||||
$this->host = $address;
|
||||
$this->port = $port;
|
||||
return $this->socketHandler->connect($address, $port);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler, uses stored connection data to fork a new instance of itself.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @throws \JPT\SocketFramework\Exception\GeneralException
|
||||
* @return \JPT\SocketFramework\Connection\ConnectionHandler
|
||||
*/
|
||||
public function reconnect() {
|
||||
if($this->reconnectOnDisconnect === FALSE) throw new \JPT\SocketFramework\Exception\GeneralException("Cannot reconnect: Reconnect-Flag not set!", 1290951385);
|
||||
if(empty($this->host) === TRUE) throw new \JPT\SocketFramework\Exception\GeneralException("Cannot reconnect: No host specified.", 1290950818);
|
||||
if(empty($this->port) === TRUE) throw new \JPT\SocketFramework\Exception\GeneralException("Cannot reconnect: No port specified.", 1290950844);
|
||||
$newConnectionHandler = $this->connectionPool->createTcpConnection($this->group, $this->protocol, $this->IPv6);
|
||||
$newConnectionHandler->setReconnect($this->getReconnect());
|
||||
$newConnectionHandler->connect($this->host, $this->port);
|
||||
return $newConnectionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function bind($address, $port) {
|
||||
$this->host = $address;
|
||||
$this->port = $port;
|
||||
return $this->socketHandler->bind($address, $port);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function listen() {
|
||||
$this->isServer = TRUE;
|
||||
return $this->socketHandler->listen();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @return boolean
|
||||
*/
|
||||
public function isConnected() {
|
||||
return $this->socketHandler->isConnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the is_connected-flag in the socket handler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @param boolean $connected
|
||||
* @return void
|
||||
*/
|
||||
protected function setConnected($connected) {
|
||||
return $this->socketHandler->setConnected($connected);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @return boolean
|
||||
*/
|
||||
public function isListening() {
|
||||
return $this->socketHandler->isListening();
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return ressource
|
||||
*/
|
||||
public function getSocket() {
|
||||
return $this->socketHandler->getSocket();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \JPT\SocketFramework\Socket\SocketHandler
|
||||
*/
|
||||
public function getSocketHandler() {
|
||||
return $this->socketHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls SocketHandler.
|
||||
*
|
||||
* @see \JPT\SocketFramework\Socket\SocketHandler
|
||||
* @return void
|
||||
*/
|
||||
public function hasBeenAccepted() {
|
||||
return $this->socketHandler->hasBeenAccepted();
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Connection;
|
||||
|
||||
/**
|
||||
* Connection pool class. Contains the SocketPool.
|
||||
*
|
||||
* @author jpt
|
||||
* @package Connection
|
||||
* @depends Socket
|
||||
*/
|
||||
class ConnectionPool {
|
||||
|
||||
/**
|
||||
* SocketPool instance.
|
||||
*
|
||||
* @var \JPT\SocketFramework\Socket\SocketPool
|
||||
*/
|
||||
protected $socketPool;
|
||||
|
||||
/**
|
||||
* Contains all ConnectionHandler instances.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $connectionHandlers;
|
||||
|
||||
/**
|
||||
* @var int Next ID for a new ConnectionHandler
|
||||
*/
|
||||
protected $nextID;
|
||||
|
||||
/**
|
||||
* Creates an Instance of SocketPool.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->connectionHandlers = array();
|
||||
$this->socketPool = new \JPT\SocketFramework\Socket\SocketPool();
|
||||
$this->nextID = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the SocketPool.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __destruct() {
|
||||
unset($this->socketPool);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new TcpConnection.
|
||||
*
|
||||
* @param boolean $IPv6 will determine whether the socket uses IPv4 or IPv6.
|
||||
* @return \JPT\SocketFramework\Connection\ConnectionHandler
|
||||
*/
|
||||
public function createTcpConnection($group = "", $protocol = "RAW", $IPv6 = FALSE) {
|
||||
$socket = $this->socketPool->createTcpSocket($IPv6);
|
||||
$connectionHandler = new \JPT\SocketFramework\Connection\ConnectionHandler($socket, $this->nextID, $group, $protocol);
|
||||
$connectionHandler->setIPv6($IPv6);
|
||||
$connectionHandler->injectConnectionPool($this);
|
||||
$this->addConnectionHandler($connectionHandler);
|
||||
return $connectionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the array with the current connectionHandlers.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getConnectionHandlers() {
|
||||
return $this->connectionHandlers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a ConnectionHandler to the pool.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $addConnectionHandler
|
||||
* @return void
|
||||
*/
|
||||
public function addConnectionHandler($addConnectionHandler) {
|
||||
array_push($this->connectionHandlers, $addConnectionHandler);
|
||||
$this->nextID++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a ConnectionHandler from the pool.
|
||||
*
|
||||
* @param \JPT\SocketFramework\Connection\ConnectionHandler $removeConnectionHandler
|
||||
* @return void
|
||||
*/
|
||||
public function removeConnectionHandler($removeConnectionHandler) {
|
||||
foreach($this->connectionHandlers AS $key=>$connectionHandler) {
|
||||
if($connectionHandler === $removeConnectionHandler) {
|
||||
$this->socketPool->removeSocket($removeConnectionHandler->getSocket());
|
||||
$removeConnectionHandler->close();
|
||||
unset($this->connectionHandlers[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns ConnectionHandler for the given socket ressource.
|
||||
*
|
||||
* @param ressource $socketRessource
|
||||
* @return \JPT\SocketFramework\Connection\ConnectionHandler
|
||||
*/
|
||||
protected function getConnectionHandlerForSocketRessource($socketRessource) {
|
||||
foreach($this->connectionHandlers AS $connectionHandler) {
|
||||
if($connectionHandler->getSocket() === $socketRessource) {
|
||||
return $connectionHandler;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls select() on SocketPool and updates the ConnectionHandler.
|
||||
* Will also accept incoming connections and add them to the pool.
|
||||
*
|
||||
* @return array An array containing the ConnectionHandler for each Socket with new data.
|
||||
* @throws \JPT\SocketFramework\Exception\GeneralException
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
*/
|
||||
public function select() {
|
||||
$read = array();
|
||||
$write = array();
|
||||
$except = array();
|
||||
foreach($this->connectionHandlers AS $connectionHandler) {
|
||||
$connectionSocket = $connectionHandler->getSocket();
|
||||
$read[] = $connectionSocket;
|
||||
if($connectionHandler->canWrite() === TRUE && $connectionHandler->isServer() === FALSE) {
|
||||
$write[] = $connectionSocket;
|
||||
//the line above does not work for freshly connected stuff.
|
||||
//this is the fallback - just write the stuff - no matter what happens.
|
||||
if($connectionHandler->writeFromBuffer() === FALSE) $this->removeConnectionHandler($connectionHandler);
|
||||
}
|
||||
}
|
||||
$except = $read;
|
||||
|
||||
//Arrays are prepared, let's have socket_select() take a look and process its results.
|
||||
$tempArray = array();
|
||||
$selectedSockets = $this->socketPool->select($read, $write, $except);
|
||||
foreach($selectedSockets AS $selectedType=>$selectedArray) { //read, write, except, this loop won't kill performance
|
||||
foreach($selectedArray AS $socket) {
|
||||
$connectionHandler = $this->getConnectionHandlerForSocketRessource($socket);
|
||||
switch($selectedType) {
|
||||
case "read":
|
||||
if($connectionHandler->isServer() === TRUE) {
|
||||
$acceptedSocket = $connectionHandler->accept();
|
||||
$acceptedSocketHandler = new \JPT\SocketFramework\Connection\ConnectionHandler($acceptedSocket, $this->nextID, $connectionHandler->getGroup(), $connectionHandler->getProtocol());
|
||||
$acceptedSocketHandler->hasBeenAccepted();
|
||||
$this->addConnectionHandler($acceptedSocketHandler);
|
||||
} else {
|
||||
$connectionHandler->readToBuffer();
|
||||
}
|
||||
break;
|
||||
case "write":
|
||||
//this might still work on active connections that are "in use" and already received data.
|
||||
//however, it does not for freshly connected ones.
|
||||
if($connectionHandler->writeFromBuffer() === FALSE) $this->removeConnectionHandler($connectionHandler);
|
||||
break;
|
||||
case "except":
|
||||
$connectionHandler->handleSocketError();
|
||||
break;
|
||||
default:
|
||||
throw new Exception_GeneralException("Unknown select type: '" . $selectedType . "'", 1289737080);
|
||||
break;
|
||||
}
|
||||
//Put the ConnectionHandler into the array. We'll return this for further operations.
|
||||
$tempArray[$selectedType][] = $connectionHandler;
|
||||
}
|
||||
}
|
||||
return $tempArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the given data to all sockets in $group.
|
||||
*
|
||||
* @param string $group
|
||||
* @param string $data
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function writeToGroup($group, $data) {
|
||||
foreach($this->connectionHandlers AS $connectionHandler) {
|
||||
if($connectionHandler->getGroup() === $group && $connectionHandler->isServer() === FALSE) {
|
||||
$connectionHandler->write($data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the given data to the socket with $id.
|
||||
*
|
||||
* @param int $id
|
||||
* @param string $data
|
||||
* @return void
|
||||
*/
|
||||
public function writeToID($id, $data) {
|
||||
foreach($this->connectionHandlers AS $connectionHandler) {
|
||||
if($connectionHandler->getID() === $id && $connectionHandler->isServer() === FALSE) {
|
||||
$connectionHandler->write($data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see \JPT\SocketFramework\Socket\SocketPool
|
||||
* @return int
|
||||
*/
|
||||
public function countSockets() {
|
||||
return $this->socketPool->countSockets();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the amount of active connections.
|
||||
* A connection is active when the handler is connected.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function countActiveConnections() {
|
||||
$count = 0;
|
||||
foreach($this->connectionHandlers AS $connectionHandler) {
|
||||
if($connectionHandler->isConnected() === TRUE) $count++;
|
||||
}
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Core;
|
||||
|
||||
/**
|
||||
* Simple class to capsule the classloader so more than one autoload function can be used.
|
||||
*
|
||||
* @author JPT
|
||||
*/
|
||||
class ClassLoader {
|
||||
|
||||
/**
|
||||
* Autoloader function.
|
||||
* All classes will be in Classes/$Package$/$ClassName$.php
|
||||
*
|
||||
* @throws \Exception
|
||||
* @param string $className
|
||||
* @return void
|
||||
*/
|
||||
public function loadClass($className) {
|
||||
if(substr($className, 0, 19) !== "JPT\\SocketFramework") return;
|
||||
$className = substr($className, 20);
|
||||
$fileName = "SocketFramework" . \DIRECTORY_SEPARATOR . "Classes";
|
||||
$fileName .= \DIRECTORY_SEPARATOR . str_replace("\\", \DIRECTORY_SEPARATOR, $className) . ".php";
|
||||
|
||||
if(file_exists($fileName) === TRUE) {
|
||||
require_once($fileName);
|
||||
} else {
|
||||
throw new \Exception("Could not load class: '" . $className . "' - File does not exist: '" . $fileName . "'!", 1289659295);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple function that registers loadClass as an autoloader.
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception in case spl_autoload_register fails.
|
||||
*/
|
||||
public function initialize() {
|
||||
spl_autoload_register(array($this, 'loadClass'), TRUE, TRUE);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Exception;
|
||||
|
||||
/**
|
||||
* General exception.
|
||||
*
|
||||
* @author jpt
|
||||
* @package Exception
|
||||
* @exception
|
||||
*/
|
||||
class GeneralException extends \Exception {
|
||||
|
||||
/**
|
||||
* Constructor. Throws a new exception in case the exception is unknown.
|
||||
*
|
||||
* @throws UnknownException
|
||||
* @param string $message
|
||||
* @param int $code
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($message = "", $code = 0) {
|
||||
if ($message === "") {
|
||||
throw new $this('Unknown '. get_class($this));
|
||||
}
|
||||
parent::__construct($message, $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts all the important information into a string.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function __toString() {
|
||||
$string = get_class($this);
|
||||
$string .= " :" . $this->message;
|
||||
$string .= " in " . $this->file . "(" . $this->line . ")";
|
||||
$string .= PHP_EOL . $this->getTraceAsString();
|
||||
return $string;
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Exception;
|
||||
|
||||
/**
|
||||
* SocketException
|
||||
*
|
||||
* @author jpt
|
||||
* @package Exception
|
||||
* @exception
|
||||
*/
|
||||
class SocketException extends GeneralException {}
|
||||
?>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Exception;
|
||||
|
||||
/**
|
||||
* WrongDatatypeException
|
||||
*
|
||||
* @author jpt
|
||||
* @package Exception
|
||||
* @exception
|
||||
*/
|
||||
class WrongDatatypeException extends GeneralException {}
|
||||
?>
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Misc;
|
||||
|
||||
/**
|
||||
* Buffer class for a string.
|
||||
* Will fix issues with sockets that don't care about linebreaks.
|
||||
* Can also be used for all kinds of purpose.
|
||||
*
|
||||
* @author jpt
|
||||
* @package Misc
|
||||
*/
|
||||
class Buffer {
|
||||
|
||||
/**
|
||||
* Bufferstring - contains all the data.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $buffer;
|
||||
|
||||
/**
|
||||
* Linebreak to use for pulling lines out of the buffer.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $linebreak;
|
||||
|
||||
/**
|
||||
* Default constructor. Sets a default linebreak and initializes the buffer.
|
||||
*
|
||||
* @param $linebreak
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($linebreak = "") {
|
||||
$this->buffer = "";
|
||||
$this->linebreak = $linebreak;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prunes empty lines out of the buffer.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function pruneEmptyLines() {
|
||||
//no need to do this when there are no linebreaks.
|
||||
if($this->linebreak === "") return;
|
||||
if(strpos($this->buffer, $this->linebreak) === FALSE) return;
|
||||
$hasLinebreakAtEnd = (substr($this->buffer, (-1) * strlen($this->linebreak)) === $this->linebreak) ? TRUE : FALSE;
|
||||
$lines = explode($this->linebreak, $this->buffer);
|
||||
foreach($lines AS $key=>$line) {
|
||||
$line = str_replace($this->linebreak, "", $line);
|
||||
$line = trim($line);
|
||||
if($line === "") unset($lines[$key]);
|
||||
}
|
||||
$this->buffer = implode($this->linebreak, $lines);
|
||||
if($hasLinebreakAtEnd === TRUE) $this->buffer .= $this->linebreak;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends data to the buffer.
|
||||
*
|
||||
* @param string $data
|
||||
* @return void
|
||||
*/
|
||||
public function addData($data) {
|
||||
$this->buffer .= $data;
|
||||
$this->pruneEmptyLines();
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends data + linebreak to the buffer.
|
||||
*
|
||||
* @param string $data
|
||||
* @return void
|
||||
*/
|
||||
public function addLine($data) {
|
||||
$this->buffer .= $data . $this->linebreak;
|
||||
$this->pruneEmptyLines();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the next line in the buffer and removes it from the buffer.
|
||||
*
|
||||
* @return string
|
||||
* @throws Exception_GeneralException
|
||||
*/
|
||||
public function getNextLine() {
|
||||
if($this->linebreak === "") throw new Exception_GeneralException("Cannot return a line - no linebreak is set!", 1290964174);
|
||||
if(!$this->hasLines()) return "";
|
||||
list($line) = explode($this->linebreak, $this->buffer);
|
||||
$this->buffer = str_replace($line.$this->linebreak, "", $this->buffer);
|
||||
$line = trim($line);
|
||||
$result = ($line !== "") ? $line.$this->linebreak : "";
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the length of the buffer.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getBufferLength() {
|
||||
return strlen($this->buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the next $length chars from the buffer or throws an exception if this cannot be done.
|
||||
*
|
||||
* @throws Exception_GeneralException
|
||||
* @return string
|
||||
*/
|
||||
public function getNextChars($length) {
|
||||
if(strlen($this->buffer) < $length) throw new \JPT\SocketFramework\Exception\GeneralException("Cannot return ".$length." chars, there are only ".strlen($this->buffer)." chars left!", 1292780386);
|
||||
$data = substr($this->buffer, 0, $length);
|
||||
$this->buffer = substr($this->buffer, $length);
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the buffer contains more lines to process.
|
||||
*
|
||||
* @return boolean
|
||||
* @throws Exception_GeneralException
|
||||
*/
|
||||
public function hasLines() {
|
||||
if($this->linebreak === "") throw new \JPT\SocketFramework\Exception\GeneralException("Cannot tell whether the buffer has lines - no linebreak set!", 1290964243);
|
||||
return (trim(strstr($this->buffer, $this->linebreak, TRUE)) !== "") ? TRUE : FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE when there is data in the buffer.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function hasData() {
|
||||
return (strlen($this->buffer) > 0) ? TRUE : FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the full buffer contents.
|
||||
* Also truncates the buffer.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAllBufferContents() {
|
||||
$return = $this->buffer;
|
||||
$this->buffer = "";
|
||||
return $return;
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,246 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Socket;
|
||||
|
||||
/**
|
||||
* The SocketHandler class will handle a single socket.
|
||||
* It takes care of the very basic socket functions.
|
||||
*
|
||||
* @author jpt
|
||||
* @package Socket
|
||||
*/
|
||||
class SocketHandler {
|
||||
|
||||
/**
|
||||
* Socket ressource
|
||||
*
|
||||
* @var ressource
|
||||
*/
|
||||
protected $socket;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $isConnected;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $isBound;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $isListening;
|
||||
|
||||
/**
|
||||
* Default constructor. Sets the socket.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param ressource $socket
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($socket) {
|
||||
if(is_resource($socket) === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("Invalid socket ressource!", 1289663108);
|
||||
$this->socket = $socket;
|
||||
$this->isBound = FALSE;
|
||||
$this->isConnected = FALSE;
|
||||
$this->isListening = FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destructor. Closes socket.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __destruct() {
|
||||
$this->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns socket.
|
||||
*
|
||||
* @return ressource
|
||||
*/
|
||||
public function getSocket() {
|
||||
return $this->socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function isConnected() {
|
||||
return $this->isConnected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets isConnected-flag.
|
||||
*
|
||||
* @param boolean $connected
|
||||
* @return void
|
||||
*/
|
||||
public function setConnected($connected) {
|
||||
$this->isConnected = $connected;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function isListening() {
|
||||
return $this->isListening;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to a specified address.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param string $address
|
||||
* @param int $port
|
||||
* @return void
|
||||
*/
|
||||
public function connect($address, $port) {
|
||||
if($this->isConnected === TRUE) throw new \JPT\SocketFramework\Exception\SocketException("Socket is already connected!", 1289663170);
|
||||
$result = socket_connect($this->socket, $address, $port);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
$this->isConnected = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the socket to an address + port.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param string $address
|
||||
* @param int $port
|
||||
* @return void
|
||||
*/
|
||||
public function bind($address, $port) {
|
||||
if($this->isBound === TRUE) throw new \JPT\SocketFramework\Exception\SocketException("Socket is already bound!", 1289663212);
|
||||
$result = socket_set_option($this->socket, \SOL_SOCKET, \SO_REUSEADDR, 1);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
$result = socket_bind($this->socket, $address, $port);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
$this->isBound = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Let's the socket listen for incoming connections.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function listen() {
|
||||
if($this->isBound === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("Cannot listen on unbound socket!", 1289663220);
|
||||
$result = socket_listen($this->socket);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
$this->isListening = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the SocketHandler that he got accepted.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function hasBeenAccepted() {
|
||||
$this->isConnected = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts a connection to a socket that is bound and listens.
|
||||
* The ressource has to be added to the SocketPool manually.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return ressource
|
||||
*/
|
||||
public function accept() {
|
||||
if($this->isBound === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("Cannot accept connections from unbound socket!", 1289663239);
|
||||
if($this->isListening === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("Cannot accept connections from socket that is not listening!", 1289663241);
|
||||
$accept = socket_accept($this->socket);
|
||||
if($accept === FALSE) $this->handleSocketError();
|
||||
return $accept;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns ip + port of the remote socket.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return string
|
||||
*/
|
||||
public function getRemoteName() {
|
||||
if($this->isConnected === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("Socket not connected, cannot retrieve remote name!", 1289928192);
|
||||
$result = socket_getpeername($this->socket, $address, $port);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
return $address . ":" . $port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns ip + port of the local socket.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return string
|
||||
*/
|
||||
public function getLocalName() {
|
||||
if($this->isBound === FALSE ^ $this->isConnected === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("Socket is not bound or connected, no local name available!", 1289928256);
|
||||
$result = socket_getsockname($this->socket, $address, $port);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
return $address . ":" . $port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes data to the socket.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param string $data
|
||||
* @return void
|
||||
*/
|
||||
public function write($data) {
|
||||
$result = socket_write($this->socket, $data);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads data from the socket.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param int $length
|
||||
* @return string
|
||||
*/
|
||||
public function read($length = 16384) {
|
||||
$result = socket_read($this->socket, $length, \PHP_BINARY_READ);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts the socket down after waiting a bit (waiting might be optional).
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
public function close() {
|
||||
usleep(100000); //we'll wait here since socket_shutdown _might_ fail without it.
|
||||
if($this->isConnected === TRUE) {
|
||||
$result = socket_shutdown($this->socket);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
}
|
||||
if(is_resource($this->socket)) {
|
||||
$result = socket_close($this->socket);
|
||||
if($result === FALSE) $this->handleSocketError();
|
||||
}
|
||||
$this->isConnected = FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets last error from socket.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return void
|
||||
*/
|
||||
protected function handleSocketError() {
|
||||
if(is_resource($this->socket) === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("No socket resource available!", 1290954177);
|
||||
$errno = socket_last_error($this->socket);
|
||||
$error = socket_strerror($errno);
|
||||
socket_clear_error();
|
||||
$errormsg = "[" . $errno . "] " . $error;
|
||||
throw new \JPT\SocketFramework\Exception\SocketException("A socket error occured: " . $errormsg, 1289663360);
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
namespace JPT\SocketFramework\Socket;
|
||||
|
||||
/**
|
||||
* The SocketPool class that will handle all the sockets.
|
||||
* Manages a pool of socket ressources with socket_select().
|
||||
*
|
||||
* @author jpt
|
||||
* @package Socket
|
||||
*/
|
||||
class SocketPool {
|
||||
|
||||
/**
|
||||
* Pool that contains socket ressources.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $sockets;
|
||||
|
||||
/**
|
||||
* Creates sockets.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->sockets = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes all connections.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __destruct() {
|
||||
unset($this->sockets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the amount of active sockets.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function countSockets() {
|
||||
return count($this->sockets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a socket to the pool.
|
||||
*
|
||||
* @param ressource $addSocket
|
||||
* @return void
|
||||
*/
|
||||
public function addSocket($addSocket) {
|
||||
array_push($this->sockets, $addSocket);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the given socket from the pool.
|
||||
* The socket will be shutdown.
|
||||
*
|
||||
* @param ressource $removeSocket
|
||||
* @return void
|
||||
*/
|
||||
public function removeSocket($removeSocket) {
|
||||
foreach($this->sockets AS $key=>$socket) {
|
||||
if($socket !== $removeSocket) {
|
||||
continue;
|
||||
} else {
|
||||
unset($socket);
|
||||
unset($this->sockets[$key]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new TcpSocket and adds it to the pool.
|
||||
*
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @param boolean $IPv6 will determine whether the socket uses IPv4 or IPv6.
|
||||
* @return ressource
|
||||
*/
|
||||
public function createTcpSocket($IPv6 = FALSE) {
|
||||
$domain = ($IPv6) ? \AF_INET6 : \AF_INET;
|
||||
$socket = socket_create($domain, \SOCK_STREAM, \SOL_TCP);
|
||||
socket_set_block($socket);
|
||||
if($socket === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("socket_create() failed!", 1290273709);
|
||||
$this->addSocket($socket);
|
||||
return $socket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array of sockets one can read from.
|
||||
*
|
||||
* @param array $read
|
||||
* @param array $write
|
||||
* @param array $except
|
||||
* @param int $timeout
|
||||
* @throws \JPT\SocketFramework\Exception\SocketException
|
||||
* @return array
|
||||
*/
|
||||
public function select($read, $write, $except, $timeout = NULL) {
|
||||
$n = socket_select($read, $write, $except, $timeout);
|
||||
if($n === FALSE) throw new \JPT\SocketFramework\Exception\SocketException("socket_select() failed! - Error: " . socket_strerror(socket_last_error()), 1290273693);
|
||||
if($n === 0) return array("read" => array(), "write" => array(), "except" => array());
|
||||
return array("read" => $read, "write" => $write, "except" => $except);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user