write data to socket

@param   string  $data  data to write
@return  int  amount of bytes written to socket
@throws  \stubbles\peer\ConnectionFailure
@throws  \stubbles\peer\Timeout
172305
public function write(string $data): int
    {
        $length = fputs($this->resource, $data, strlen($data));
        if (false === $length) {
            if (stream_get_meta_data($this->resource)['timed_out']) {
                throw new Timeout(
                        'Writing of ' . strlen($data) . ' bytes failed:'
                        . ' timeout of ' . $this->timeout . ' seconds exceeded'
                );
            }

            throw new ConnectionFailure(
                    'Writing of ' . strlen($data) . ' bytes failed.'
            );
        }

        return $length;
    }
1369318
public function writeBytes($data)
    {
        if ($this->isClosed) {
            // TODO: Should this be an error condition? e.g. BadMethodCallException
            return;
        }

        $bytesRead = 0;

        while ($bytesRead != strlen($data)) {
            $initialBufferLength = strlen($this->buffer);
            $this->buffer .= substr($data, $bytesRead, $this->chunkSize - $initialBufferLength);
            $bytesRead += strlen($this->buffer) - $initialBufferLength;

            if (strlen($this->buffer) == $this->chunkSize) {
                $this->insertChunkFromBuffer();
            }
        }

        return $bytesRead;
    }
261264
protected function _writeStream($buffer) {
        $fd = $this->socket_;
        $total = TStringFuncFactory::create()->strlen($buffer);

        // Early out on the trivial case
        if ($total <= 0) {
            return;
        }

        $failed = FALSE;
        $sent = 0;

        while (!$failed && $sent < $total) {

            if (!is_resource($fd)) {
                $failed = TRUE;
            }

            try {
                // Supress any error messages as it is considered part of normal
                // operation for the write to fail on a broken pipe or timeout
                $written = @fwrite($fd, $buffer, self::MAX_BYTES_PER_WRITE);

                if ($written > 0){
                    $sent += $written;
                    $buffer = substr($buffer, $written);

                } else if ($written === FALSE) {
                    if ($this->debug_) {
                        error_log("Write failed.");
                    }
                    $failed = TRUE;

                } else if ($written === 0) {
                    if ($this->debug_) {
                        error_log("Zero bytes written to socket. sent=$sent total=$total");
                    }
                    $failed = TRUE;
                } else {
                    if ($this->debug_) {
                        error_log("Unexpected fwrite return value '$written'");
                    }
                    $failed = TRUE;
                }

                if ($this->debug_) {
                    error_log("Written = $written bytes. Sent $sent of $total.");
                }

            } catch (Exception $e) {
                if ($this->debug_) {
                    error_log($e);
                }
                $failed = TRUE;
            }
        }

        if ($failed) {
            $this->_closeSocket();
        }
    }
632373
public function sendData($data)
    {
        if ($this->isConnected()) {
            if (socket_write($this->socket, $data, strlen($data)) === false) {
                $this->eventManager()->fire('onClose',
                   [
                        $this->phoneNumber,
                        'Connection closed!',
                    ]
              );
            }
        }
    }
667337
public function data($data)
    {
        if($this->state == Connection::READ_HEADERS) {
            if(!$this->start_time) $this->start_time = microtime(true);
            $this->header_buffer .= $data;

            $end = strpos($this->header_buffer, "\r\n\r\n", 4);
            if($end === false) return;

            // parse HTTP request
            $this->parse_request(substr($this->header_buffer, 0, $end));

            // TODO: check for Transfer-Encoding: chunked

            $this->content_length = (int)$this->get_header('Content-Length');

            $body_start = $end + 4;
            $data = substr($this->header_buffer, $body_start);

            $this->state = Connection::READ_CONTENT;
        }

        if($this->state == Connection::READ_CONTENT) {
            if($this->is_chunked) {
                // TODO: Handle chunked data
            } else {
                fwrite($this->body, $data);
                $this->bytes_read += strlen($data);

                if($this->content_length - $this->bytes_read <= 0) $this->state = Connection::READ_COMPLETE;
            }
        }

        if($this->state == Connection::READ_COMPLETE) fseek($this->body, 0);
    }
1145968
public void write(final String data) throws IOException {
        if (socket != null) {
            out.write(data.getBytes());
        }
    }
378381
public function write($data): void
    {
        $rand = \random_int(0, 28);
        $frame = [
            'fin' => 1,
            'rsv1' => 0,
            'rsv2' => 0,
            'rsv3' => 0,
            'opcode' => 1, // We always send text
            'mask' => 1,
            'len' => \strlen($data),
            'mask_key' => \substr(\md5(\uniqid()), $rand, 4),
            'data' => $data,
        ];

        if (1 === $frame['mask']) {
            for ($i = 0; $i < $frame['len']; ++$i) {
                $frame['data'][$i]
                    = \chr(\ord($frame['data'][$i]) ^ \ord($frame['mask_key'][$i % 4]));
            }
        }

        if ($frame['len'] > 2 ** 16) {
            $len = 127;
        } elseif ($frame['len'] > 125) {
            $len = 126;
        } else {
            $len = $frame['len'];
        }

        $firstByte = ($frame['fin'] << 7) | (($frame['rsv1'] << 7) >> 1) | (($frame['rsv2'] << 7) >> 2) | (($frame['rsv3'] << 7) >> 3) | (($frame['opcode'] << 4) >> 4);
        $secondByte = ($frame['mask'] << 7) | (($len << 1) >> 1);

        $this->socketWrite(\chr($firstByte));
        $this->socketWrite(\chr($secondByte));

        if (126 === $len) {
            $this->socketWrite(\pack('n', $frame['len']));
        } elseif (127 === $len) {
            $higher = $frame['len'] >> 32;
            $lower = ($frame['len'] << 32) >> 32;
            $this->socketWrite(\pack('N', $higher));
            $this->socketWrite(\pack('N', $lower));
        }

        if (1 === $frame['mask']) {
            $this->socketWrite($frame['mask_key']);
        }

        $this->socketWrite($frame['data']);
    }
278645
protected function _write($data) {
        if (is_null($this->_varnishConn)) {
            $this->_connect();
        }
        $data = rtrim($data).PHP_EOL;
        $dataLength = strlen($data);
        if ($dataLength >= self::CLI_CMD_LENGTH_LIMIT) {
            $cliBufferResponse = $this->param_show('cli_buffer');
            $regexp = '~^cli_buffer\s+(\d+)\s+\[bytes\]~';
            if ($this->getVersion() === '4.0' || $this->getVersion() === '4.1') {
                // Varnish4 supports "16k" style notation
                $regexp = '~^cli_buffer\s+Value is:\s+(\d+)([k|m|g|b]{1})?\s+\[bytes\]~';
            }
            if (preg_match($regexp, $cliBufferResponse['text'], $match)) {
                $realLimit = (int) $match[1];
                if (isset($match[2])) {
                    $factors = array('b'=>0, 'k'=>1, 'm'=>2, 'g'=>3);
                    $realLimit *= pow(1024, $factors[$match[2]]);
                }
            } else {
                Mage::helper('turpentine/debug')->logWarn(
                    'Failed to determine Varnish cli_buffer limit, using default' );
                $realLimit = self::CLI_CMD_LENGTH_LIMIT;
            }
            if ($dataLength >= $realLimit) {
                Mage::throwException(sprintf(
                    'Varnish data to write over length limit by %d characters',
                    $dataLength - $realLimit ));
            }
        }
        if (($byteCount = fwrite($this->_varnishConn, $data)) !== $dataLength) {
            Mage::throwException(sprintf('Varnish socket write error: %d != %d',
                $byteCount, $dataLength));
        }
        return $this;
    }
930303
def write(data, timeout = @timeout)
      full_size = data.bytesize

      while data.bytesize > 0
        written = socket.write_nonblock(data, exception: false)

        if written == :wait_writable
          socket.wait_writable(timeout) or fail_with_timeout!
        else
          data = data.byteslice(written..-1)
        end
      end

      full_size
    end
590239
public function write(string $data): int
    {
        if (!$this->connected()) {
            throw new LogicException('Not connected');
        }

        return (int) fwrite($this->connection, $data, strlen($data));
    }
942399
public function write($buffer)
    {
        $ret = @socket_write($this->resource, $buffer);
        if ($ret === false) {
            throw Exception::createFromSocketResource($this->resource);
        }
        return $ret;
    }
783208
public function write($data = null) {
		if (!is_resource($this->_resource)) {
			return false;
		}
		if (!is_object($data)) {
			$data = $this->_instance($this->_classes['request'], (array) $data + $this->_config);
		}
		return fwrite($this->_resource, (string) $data, strlen((string) $data));
	}
1098865
def write(self, data):
        '''
        
        '''
        if not hasattr(self, '_sock'):
            return None

        try:
            self._sock.sendall(data)

            if self.connection.debug > 1:
                self.connection.logger.debug(
                    'sent %d bytes to %s' % (len(data), self._host))

            return
        except EnvironmentError:
            # sockets raise this type of error, and since if sendall() fails
            # we're left in an indeterminate state, assume that any error we
            # catch means that the connection is dead. Note that this
            # assumption requires this to be a blocking socket; if we ever
            # support non-blocking in this class then this whole method has
            # to change a lot.
            self.connection.logger.exception(
                'error writing to %s' % (self._host))

        self.connection.transport_closed(
            msg='error writing to %s' % (self._host))
544296
public function write(string $bytes): int
    {
        $isAcceptable = $this->predicate;
        if ($isAcceptable($bytes)) {
            return $this->outputStream->write($bytes);
        }

        return 0;
    }
636480
public function client_send($data)
    {
        if ($this->do_debug >= 1) {
            $this->edebug("CLIENT -> SERVER: $data");
        }
        return fwrite($this->smtp_conn, $data);
    }
12097
def write(self, data):
        """"""
        # If nobody is connected, act like all data was written anyway.
        if self.connected is None:
            return 0
        data = to_bytes_safe(data)
        size = len(data)
        remaining = size
        while remaining:
            count = self._abstract_socket.write(data)
            remaining -= count
            if remaining:
                data = data[count:]
        return size
14561
public function write($data)
    {
        if ($this->isOpen() === false) {
            $msg = "Cannot write in a closed MemoryStream.";
            throw new MemoryStreamException($msg, $this, MemoryStreamException::NOT_OPEN);
        }
        
        if ($this->length - 1 === $this->position) {
            // simply append.
            $this->binary .= $data;
        } elseif ($this->position === 0) {
            // simply prepend.
            $this->binary = ($data . $this->binary);
        } else {
            // we are in the middle of the string.
            $part1 = substr($this->binary, 0, $this->position);
            $part2 = substr($this->binary, $this->position);
            $this->binary = ($part1 . $data . $part2);
        }

        $dataLen = strlen($data);
        $this->incrementPosition($dataLen);
        $this->incrementLength($dataLen);

        return $dataLen;
    }