*/
private $sentData = 0;
- /**
- * Difference
- */
- private $diff = 0;
-
/**
* Whether this connection is initialized
*/
// Call parent constructor
parent::__construct($className);
+ // Init state which sets the state to 'init'
+ $this->initState();
+
// Initialize output stream
$streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_output_stream_class');
// And add it to this connection helper
$this->setOutputStreamInstance($streamInstance);
- // Init state which sets the state to 'init'
- $this->initState();
+ // Get package instance from factory
+ $packageInstance = NetworkPackageFactory::createNetworkPackageInstance();
+
+ // ... and set it here
+ $this->setPackageInstance($packageInstance);
// Register this connection helper
Registry::getRegistry()->addInstance('connection', $this);
* @return void
*/
private function initState() {
- /*
- * Get the state factory and create the initial state, we don't need
- * the state instance here
- */
+ // Get the state factory and create the initial state.
PeerStateFactory::createPeerStateInstanceByName('init', $this);
}
* The rest is being held in a back-buffer and waits there for the next
* cycle and while be then sent.
*
- * This method does 4 simple steps:
- * 1) Aquire fragmenter object instance from the factory
- * 2) Handle over the package data array to the fragmenter
- * 3) Request a chunk
- * 4) Finally return the chunk (array) to the caller
+ * This method does 2 simple steps:
+ * 1) Request a chunk from set fragmenter instance
+ * 2) Finally return the chunk (array) to the caller
*
* @param $packageData Raw package data array
* @return $chunkData Raw data chunk
*/
private function getRawDataFromPackageArray (array $packageData) {
- // Implode the package data array and fragement the resulting string, returns the final hash
- $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
- if ($finalHash !== TRUE) {
- $this->currentFinalHash = $finalHash;
- } // END - if
-
// Debug message
//* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: currentFinalHash=' . $this->currentFinalHash);
+ // Make sure the final hash is set
+ assert((is_string($this->currentFinalHash)) && (!empty($this->currentFinalHash)));
+
// Get the next raw data chunk from the fragmenter
$rawDataChunk = $this->getFragmenterInstance()->getNextRawDataChunk($this->currentFinalHash);
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawDataChunk=' . print_r($rawDataChunk, TRUE));
+
// Get chunk hashes and chunk data
$chunkHashes = array_keys($rawDataChunk);
$chunkData = array_values($rawDataChunk);
* Sends raw package data to the recipient
*
* @param $packageData Raw package data
- * @return $totalSentBytes Total sent bytes to the peer
+ * @return void
* @throws InvalidSocketException If we got a problem with this socket
*/
public function sendRawPackageData (array $packageData) {
// The helper's state must be 'connected'
$this->getStateInstance()->validatePeerStateConnected();
- // Reset serial number
- $this->getFragmenterInstance()->resetSerialNumber();
+ // Implode the package data array and fragement the resulting string, returns the final hash
+ $finalHash = $this->getFragmenterInstance()->fragmentPackageArray($packageData, $this);
- // Cache buffer length
- $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
+ // Is the final hash set?
+ if ($finalHash !== TRUE) {
+ // Debug message
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Setting finalHash=' . $finalHash . ',currentFinalHash[' . gettype($this->currentFinalHash) . ']=' . $this->currentFinalHash);
+
+ // Set final hash
+ $this->currentFinalHash = $finalHash;
+ } // END - if
+
+ // Reset serial number
+ $this->getFragmenterInstance()->resetSerialNumber($this->currentFinalHash);
// Init variables
$rawData = '';
$dataStream = ' ';
- $totalSentBytes = 0;
// Fill sending buffer with data
while (strlen($dataStream) > 0) {
// Nothing to sent is bad news, so assert on it
assert(strlen($rawData) > 0);
+ // Calculate buffer size
+ $bufferSize = $this->getConfigInstance()->getConfigEntry($this->getProtocol() . '_buffer_length');
+
// Encode the raw data with our output-stream
$encodedData = $this->getOutputStreamInstance()->streamData($rawData);
// Debug message
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: rawData()=' . strlen($rawData) . ',encodedData()=' . strlen($encodedData));
+ //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('HELPER[' . __METHOD__ . ':' . __LINE__ . ']: socketResource[]=' . gettype($this->getSocketResource()) . PHP_EOL);
+
+ // Init array
+ $encodedDataArray = array(
+ NetworkPackage::RAW_FINAL_HASH_INDEX => $this->currentFinalHash,
+ NetworkPackage::RAW_ENCODED_DATA_INDEX => $encodedData,
+ NetworkPackage::RAW_SENT_BYTES_INDEX => 0,
+ NetworkPackage::RAW_SOCKET_INDEX => $this->getSocketResource(),
+ NetworkPackage::RAW_BUFFER_SIZE_INDEX => $bufferSize,
+ NetworkPackage::RAW_DIFF_INDEX => 0
+ );
// Calculate difference
- $this->diff = $bufferSize - strlen($encodedData);
+ $diff = $encodedDataArray[NetworkPackage::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[NetworkPackage::RAW_ENCODED_DATA_INDEX]);
- // Get socket resource
- $socketResource = $this->getSocketResource();
-
- // Init sent bytes
- $sentBytes = 0;
-
- // Deliver all data
- while ($sentBytes !== FALSE) {
- // And deliver it
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sending out ' . strlen($encodedData) . ' bytes,bufferSize=' . $bufferSize . ',diff=' . $this->diff);
-
- if ($this->diff >= 0) {
- // Send all out (encodedData is smaller than or equal buffer size)
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedData, 0, ($bufferSize - $this->diff))));
- $sentBytes = socket_write($socketResource, $encodedData, ($bufferSize - $this->diff));
- } else {
- // Send buffer size out
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedData, 0, $bufferSize)));
- $sentBytes = socket_write($socketResource, $encodedData, $bufferSize);
- }
-
- // If there was an error, we don't continue here
- if ($sentBytes === FALSE) {
- // Handle the error with a faked recipientData array
- $this->handleSocketError(__METHOD__, __LINE__, $socketResource, array('0.0.0.0', '0'));
-
- // And throw it
- throw new InvalidSocketException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
- } elseif (($sentBytes == 0) && (strlen($encodedData) > 0)) {
- // Nothing sent means we are done
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
- break;
- }
-
- // The difference between sent bytes and length of raw data should not go below zero
- assert((strlen($encodedData) - $sentBytes) >= 0);
-
- // Add total sent bytes
- $totalSentBytes += $sentBytes;
-
- // Cut out the last unsent bytes
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedData) . ' bytes ...');
- $encodedData = substr($encodedData, $sentBytes);
-
- // Calculate difference again
- $this->diff = $bufferSize - strlen($encodedData);
-
- // Can we abort?
- if (strlen($encodedData) <= 0) {
- // Abort here, all sent!
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')');
- break;
- } // END - if
- } // END - while
-
- // Return sent bytes
- //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: totalSentBytes=' . $totalSentBytes . ',diff=' . $this->diff);
- return $totalSentBytes;
+ // Push raw data to the package's outgoing stack
+ $this->getPackageInstance()->getStackInstance()->pushNamed(NetworkPackage::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray);
}
/**
throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
}
+ /**
+ * Handles socket error 'connection reset by peer', but does not clear it for
+ * later debugging purposes.
+ *
+ * @param $socketResource A valid socket resource
+ * @param $recipientData An array with two elements: 0=IP number, 1=port number
+ * @return void
+ * @throws SocketConnectionException The connection attempts fails with a time-out
+ */
+ protected function socketErrorConnectionResetByPeerHandler ($socketResource, array $recipientData) {
+ // Get socket error code for verification
+ $socketError = socket_last_error($socketResource);
+
+ // Get error message
+ $errorMessage = socket_strerror($socketError);
+
+ // Shutdown this socket
+ $this->shutdownSocket($socketResource);
+
+ // Throw it again
+ throw new SocketConnectionException(array($this, $socketResource, $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET);
+ }
+
/**
* Handles socket "error" 'operation now in progress' which can be safely
* passed on with non-blocking connections.