Send byte buffer over TCP, including a length header.

@param bytes the bytes to send
@param retries number of times to retry in event of failure
@return true if the message was sent successfully
423694
public boolean sendTCPBytes(byte[] bytes, int retries) {
        try {
            ByteBuffer header = createHeader(bytes.length);

            safeWrite(header);

            ByteBuffer buffer = ByteBuffer.wrap(bytes);

            safeWrite(buffer);

        } catch (Exception e) {
            SysLog(Level.SEVERE, "Failed to send TCP bytes" + (retries > 0 ? " -- retrying " : "") + ": " + e);

            try {
                channel.close();
            } catch (IOException ioe) {
            }

            if (retries > 0) {
                try {
                    connectWithTimeout();
                } catch (Exception connectException) {
                    SysLog(Level.SEVERE, "Failed to reconnect: " + connectException);
                    return false;
                }
                return sendTCPBytes(bytes, retries - 1);
            }

            return false;
        }
        return true;
    }
734947
private void writeBufferChain(BufferChainOutputStream bufferChain, boolean compressed) {
    ByteBuffer header = ByteBuffer.wrap(headerScratch);
    header.put(compressed ? COMPRESSED : UNCOMPRESSED);
    int messageLength = bufferChain.readableBytes();
    header.putInt(messageLength);
    WritableBuffer writeableHeader = bufferAllocator.allocate(HEADER_LENGTH);
    writeableHeader.write(headerScratch, 0, header.position());
    if (messageLength == 0) {
      // the payload had 0 length so make the header the current buffer.
      buffer = writeableHeader;
      return;
    }
    // Note that we are always delivering a small message to the transport here which
    // may incur transport framing overhead as it may be sent separately to the contents
    // of the GRPC frame.
    // The final message may not be completely written because we do not flush the last buffer.
    // Do not report the last message as sent.
    sink.deliverFrame(writeableHeader, false, false, messagesBuffered - 1);
    messagesBuffered = 1;
    // Commit all except the last buffer to the sink
    List<WritableBuffer> bufferList = bufferChain.bufferList;
    for (int i = 0; i < bufferList.size() - 1; i++) {
      sink.deliverFrame(bufferList.get(i), false, false, 0);
    }
    // Assign the current buffer to the last in the chain so it can be used
    // for future writes or written with end-of-stream=true on close.
    buffer = bufferList.get(bufferList.size() - 1);
    currentMessageWireSize = messageLength;
  }
1176279
def _send_file_external_with_retry(self, http_verb, host, url, http_headers, chunk):
        
        count = 0
        retry_times = 1
        if http_verb == 'PUT':
            retry_times = SEND_EXTERNAL_PUT_RETRY_TIMES
        while True:
            try:
                return self.data_service.send_external(http_verb, host, url, http_headers, chunk)
            except requests.exceptions.ConnectionError:
                count += 1
                if count < retry_times:
                    if count == 1:  # Only show a warning the first time we fail to send a chunk
                        self._show_retry_warning(host)
                    time.sleep(SEND_EXTERNAL_RETRY_SECONDS)
                    self.data_service.recreate_requests_session()
                else:
                    raise
563341
public boolean sendTCPBytes(ByteBuffer[] srcbuffers, int length)
    {
        boolean success = false;
        try
        {
            ByteBuffer header = createHeader(length);
            ByteBuffer[] buffers = new ByteBuffer[1 + srcbuffers.length];
            buffers[0] = header;
            for (int i = 0; i < srcbuffers.length; i++)
                buffers[i + 1] = srcbuffers[i];
            if (TCPUtils.isLogging())
            {
                long t1 = System.nanoTime();
                long bytesWritten = write(buffers);
                long t2 = System.nanoTime();
                double rate = 1000.0 * 1000.0 * 1000.0 * (double) (bytesWritten) / (1024.0 * (double) (t2 - t1));
                Log(Level.INFO, "Sent " + bytesWritten + " bytes at " + rate + " Kb/s");
            }
            else
            {
                write(buffers);
            }
            success = true;
        }
        catch (Exception e)
        {
            SysLog(Level.SEVERE, "Failed to send TCP bytes: " + e);
            try { channel.close(); } catch (IOException ioe) {}
        }
        return success;
    }
935210
async def _send(self, request_bytes, body_bytes, h11_connection):
        '''
        
        '''
        await self.sock.send_all(h11_connection.send(request_bytes))
        if body_bytes is not None:
            await self.sock.send_all(h11_connection.send(body_bytes))
        await self.sock.send_all(h11_connection.send(h11.EndOfMessage()))
801701
@Override
    protected WsByteBuffer createChunkHeader(byte[] length) {
        if (!getLink().isReconnectAllowed()) {
            // use the "shared" chunk header object
            return super.createChunkHeader(length);
        }

        // must make a unique buffer to avoid data corruption during a
        // reconnect pass
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "OSC creating chunk length buffer");
        }
        WsByteBuffer header = allocateBuffer(32);
        header.put(length);
        header.put(BNFHeaders.EOL);
        header.flip();
        return header;
    }
377002
public void receivedBytesRead(int bytes) {
        if (log.isDebugEnabled()) {
            log.debug("Client received {} bytes, written {} bytes, {} messages pending", new Object[] { bytes, getWrittenBytes(), getPendingMessages() });
        }
        clientBytesRead.addAndGet(bytes);
    }
988661
public void sendBuffer(Buffer buffer) throws IOException, InterruptedException {
		checkStatus();

		// discard empty buffers
		if (buffer.size() == 0) {
			return;
		}

		Envelope envelope = createNextEnvelope();
		envelope.setBuffer(buffer);
		this.envelopeDispatcher.dispatchFromOutputChannel(envelope);
	}
1072812
@Override
    public Message deserializePayload(BitcoinPacketHeader header, ByteBuffer in) throws ProtocolException, BufferUnderflowException {
        byte[] payloadBytes = new byte[header.size];
        in.get(payloadBytes, 0, header.size);

        // Verify the checksum.
        byte[] hash;
        hash = Sha256Hash.hashTwice(payloadBytes);
        if (header.checksum[0] != hash[0] || header.checksum[1] != hash[1] ||
                header.checksum[2] != hash[2] || header.checksum[3] != hash[3]) {
            throw new ProtocolException("Checksum failed to verify, actual " +
                    HEX.encode(hash) +
                    " vs " + HEX.encode(header.checksum));
        }

        if (log.isDebugEnabled()) {
            log.debug("Received {} byte '{}' message: {}", header.size, header.command,
                    HEX.encode(payloadBytes));
        }

        try {
            return makeMessage(header.command, header.size, payloadBytes, hash, header.checksum);
        } catch (Exception e) {
            throw new ProtocolException("Error deserializing message " + HEX.encode(payloadBytes) + "\n", e);
        }
    }
257906
private void send(ByteBuffer data) {
    try {
      this.socket.send(new DatagramPacket(
              data.array(),
              data.capacity(),
              this.address));
    } catch (IOException ioe) {
      logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage());
    }
  }
1342018
public void send(byte[] buf) {
        if (log.isTraceEnabled()) {
            log.trace("send binary: {}", Arrays.toString(buf));
        }
        // send the incoming bytes
        send(Packet.build(buf));
    }
1175261
private void sendRequest(byte[] reqBytes, URLConnection connection) {
        HttpURLConnection httpconnection = (HttpURLConnection) connection;
        OutputStream out = null;
        try {
            if (connectTimeout > 0) {
                httpconnection.setConnectTimeout(connectTimeout);
            }
            if (readTimeout > 0) {
                httpconnection.setReadTimeout(readTimeout);
            }
            httpconnection.setRequestMethod("POST");
            httpconnection.setUseCaches(false);
            httpconnection.setDoInput(true);
            httpconnection.setDoOutput(true);
            httpconnection.setRequestProperty("Content-Type", serializeHandler.getProtocol()
                    .getName() + ";charset=" + NaviRpcClientConstant.ENDODING);
            httpconnection.setRequestProperty("Content-Length", StringUtil.EMPTY + reqBytes.length);
            httpconnection.connect();
            out = httpconnection.getOutputStream();
            out.write(reqBytes);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Send " + reqBytes.length + " bytes done");
            }
        } catch (Exception e) {
            throw new RpcException("Rpc send request failed - " + e.getMessage() + " on "
                    + connection.getURL(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    LOG.error("Close send request connection error");
                }
            }
        }
    }
198847
def send(self, payloads, logger, num_tries=5):
        
        from time import sleep

        backoff_interval = 1
        backoff_factor = 2

        for try_counter in xrange(0, num_tries):
            failed_messages = self.send_without_retry(payloads)

            # success!
            if not failed_messages:
                payloads = []
                break

            # output some information about the failures for debugging
            # purposes. we expect failures to be quite rare, so we can be
            # pretty verbose.
            if logger:
                for msg in failed_messages:
                    logger.warning("Failed to send message on try %d: Id=%r, "
                                   "SenderFault=%r, Code=%r, Message=%r" %
                                   (try_counter, msg['Id'],
                                    msg.get('SenderFault'), msg.get('Code'),
                                    msg.get('Message')))

            # wait a little while, in case the problem is that we're talking
            # too fast.
            sleep(backoff_interval)
            backoff_interval *= backoff_factor

            # filter out the failed payloads for retry
            retry_payloads = []
            for msg in failed_messages:
                i = int(msg['Id'])
                retry_payloads.append(payloads[i])
            payloads = retry_payloads

        if payloads:
            raise Exception('Messages failed to send to sqs after %d '
                            'retries: %s' % (num_tries, len(payloads)))
463518
public void sendMessages(byte[] data)
    {
        try
        {
            out.write(data);
            out.flush();
        }
        catch (final IOException exception)
        {
            Verbose.exception(exception);
        }
    }
1104306
private RESTResponse sendAndReceive(String header, byte[] body) throws IOException {
        // Fail before trying if socket has been closed.
        if (isClosed()) {
            throw new IOException("Socket has been closed");
        }
        
        Exception lastException = null;
        for (int attempt = 0; attempt < MAX_SOCKET_RETRIES; attempt++) {
            try {
                sendRequest(header, body);
                return readResponse();
            } catch (IOException e) {
                // Attempt to reconnect; if this fails, the server's probably down and we
                // let reconnect's IOException pass through.
                lastException = e;
                m_logger.warn("Socket error occurred -- reconnecting", e);
                reconnect();
            }
        }
        // Here, all reconnects succeeded but retries failed; something else is wrong with
        // the server or the request.
        throw new IOException("Socket error; all retries failed", lastException);
    }
40071
public synchronized boolean sendData(byte[] bytes) {
		if (bytes != null && bytes.length > 0 && !closed.get()) {
			try {
				if (listeners == null) {
					buffer.addLast(bytes);
				} else if (listeners.length == 1) {
					listeners[0].onPacket(bytes, null, false);
				} else {
					for (PacketListener listener : listeners) {
						listener.onPacket(bytes, null, false);
					}
				}
				transferedBytes.addAndGet(bytes.length);
			} catch (MoleculerError moleculerError) {
				throw moleculerError;
			} catch (Throwable error) {
				throw new MoleculerClientError("Unable to send bytes to stream listener!", error, nodeID, null);
			}
			return true;
		}
		return false;
	}
46761
public void setByteLimit(int bytes)
    {
        _byteLimit=bytes;
        
        if (bytes>=0)
        {
            _newByteLimit=true;
            _byteLimit-=_contents-_pos;
            if (_byteLimit<0)
            {
                _avail+=_byteLimit;
                _byteLimit=0;
            }
        }
        else
        {
            _newByteLimit=false;
            _avail=_contents;
            _eof=false;
        }
    }