Reads exactly n bytes from socket
    Raises SocketError if there isn't enough data
173522
def read_exactly(socket, n):
    
    data = six.binary_type()
    while len(data) < n:
        next_data = read(socket, n - len(data))
        if not next_data:
            raise SocketError("Unexpected EOF")
        data += next_data
    return data
192358
def data_from_bn(bn, min_length: nil, required_length: nil)
      raise ArgumentError, "Missing big number" if !bn

      length = BN_num_bytes(bn)
      buf = FFI::MemoryPointer.from_string("\x00"*length)
      BN_bn2bin(bn, buf)
      s = buf.read_string(length)
      s = s.rjust(min_length, "\x00") if min_length
      if required_length && s.bytesize != required_length
        raise BTCError, "Non-matching length of the number: #{s.bytesize} bytes vs required #{required_length}"
      end
      s
    end
1310099
async def read(self, n=None):
        
        if self._streamed:
            return b''
        buffer = []
        async for body in self:
            buffer.append(body)
        return b''.join(buffer)
485171
def read(self, len=1024, buffer=None):
        

        try:
            return self._wrap_socket_library_call(
                lambda: SSL_read(self._ssl.value, len, buffer), ERR_READ_TIMEOUT)
        except openssl_error() as err:
            if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
                raise_ssl_error(ERR_PORT_UNREACHABLE, err)
            raise
589139
def read(socket, n=4096):
    

    recoverable_errors = (errno.EINTR, errno.EDEADLK, errno.EWOULDBLOCK)

    if six.PY3 and not isinstance(socket, NpipeSocket):
        select.select([socket], [], [])

    try:
        if hasattr(socket, 'recv'):
            return socket.recv(n)
        if six.PY3 and isinstance(socket, getattr(pysocket, 'SocketIO')):
            return socket.read(n)
        return os.read(socket.fileno(), n)
    except EnvironmentError as e:
        if e.errno not in recoverable_errors:
            raise
998166
def __read(self):
        
        fastbuf = BytesIO()
        while self.running:
            try:
                try:
                    c = self.receive()
                except exception.InterruptedException:
                    log.debug("socket read interrupted, restarting")
                    continue
            except Exception:
                log.debug("socket read error", exc_info=True)
                c = b''
            if c is None or len(c) == 0:
                raise exception.ConnectionClosedException()
            if c == b'\x0a' and not self.__recvbuf and not fastbuf.tell():
                #
                # EOL to an empty receive buffer: treat as heartbeat.
                # Note that this may misdetect an optional EOL at end of frame as heartbeat in case the
                # previous receive() got a complete frame whose NUL at end of frame happened to be the
                # last byte of that read. But that should be harmless in practice.
                #
                fastbuf.close()
                return [c]
            fastbuf.write(c)
            if b'\x00' in c:
                #
                # Possible end of frame
                #
                break
        self.__recvbuf += fastbuf.getvalue()
        fastbuf.close()
        result = []

        if self.__recvbuf and self.running:
            while True:
                pos = self.__recvbuf.find(b'\x00')

                if pos >= 0:
                    frame = self.__recvbuf[0:pos]
                    preamble_end_match = utils.PREAMBLE_END_RE.search(frame)
                    if preamble_end_match:
                        preamble_end = preamble_end_match.start()
                        content_length_match = BaseTransport.__content_length_re.search(frame[0:preamble_end])
                        if content_length_match:
                            content_length = int(content_length_match.group('value'))
                            content_offset = preamble_end_match.end()
                            frame_size = content_offset + content_length
                            if frame_size > len(frame):
                                #
                                # Frame contains NUL bytes, need to read more
                                #
                                if frame_size < len(self.__recvbuf):
                                    pos = frame_size
                                    frame = self.__recvbuf[0:pos]
                                else:
                                    #
                                    # Haven't read enough data yet, exit loop and wait for more to arrive
                                    #
                                    break
                    result.append(frame)
                    pos += 1
                    #
                    # Ignore optional EOLs at end of frame
                    #
                    while self.__recvbuf[pos:pos + 1] == b'\x0a':
                        pos += 1
                    self.__recvbuf = self.__recvbuf[pos:]
                else:
                    break
        return result
507917
def read(read_len)
      # If we closed the connection, return nil without calling anything again to avoid EOF
      # or other errors
      return nil if @closed

      if @left_to_read
        # We hit the end of what we need to read, if this is a chunked request, then we need to check for the next chunk
        if @left_to_read <= read_len
          data = @socket.read(@left_to_read)
          @total_size += @left_to_read
          @left_to_read = nil
          @read_clfr = true
        # Reading from known buffer still
        else
          @left_to_read -= read_len
          @total_size += read_len
          data = @socket.read(read_len)
        end

      elsif @chunked
        # We finished reading the chunks, read the last 2 to get \r\n out of the way, and then find the next chunk
        if @read_clfr
          @read_clfr = nil
          @socket.read(2)
        end

        data, chunk_read = "", 0
        while true
          # Read first line to get the chunk length
          line = @socket.readline

          len = line.slice(/[0-9a-fA-F]+/) or raise Net::HTTPBadResponse.new("wrong chunk size line: #{line}")
          len = len.hex

          # Nothing left, read off the final \r\n
          if len == 0
            @socket.read(2)
            @socket.close
            @response.instance_variable_set(:@read, true)

            @closed = true
            break
          end

          # Reading this chunk will set us over the buffer amount
          # Read what we can of it (if anything), and send back what we have and queue a read for the rest
          if ( chunk_read + len ) > read_len
            can_read = len - ( ( chunk_read + len ) - read_len )

            @left_to_read = len - can_read
            @total_size += can_read

            data << @socket.read(can_read) if can_read > 0
            break
          # We can just return the chunk as-is
          else
            @total_size += len
            chunk_read += len

            data << @socket.read(len)
            @socket.read(2)
          end
        end

      # If we don't have a content length, then we need to keep reading until we run out of data
      elsif !@content_length
        data = @socket.readline

        @total_size += data.length if data
      end

      # We've finished reading, set this so Net::HTTP doesn't try and read it again
      if !data or data == ""
        @response.instance_variable_set(:@read, true)

        nil
      else
        if data.length >= @total_size and !@chunked
          @response.instance_variable_set(:@read, true)
        end

        if ENCODABLE and @encoding
          data = data.force_encoding(@encoding) if @encoding
          data = data.encode("UTF-8")
        end

        @digest.update(data)
        data
      end

    # Mark as read finished, return the last bits of data (if any)
    rescue EOFError
      @response.instance_variable_set(:@read, true)
      @socket.close
      @closed = true

      if data and data != ""
        @digest.update(data)
        data
      else
        nil
      end
    end
1063955
def recv_data(self):
        
        data, addr = self.sock.recvfrom(self.packetsize)
        matrix = map(ord, data.strip())
        if len(matrix) == self.packetsize:
            self.matrix = matrix[:-4]
338008
function readSocket(socket, numberOfBytes) {
    return new Promise((resolve, reject) => {
        let completed = createSimplePromiseCompletedAction(resolve, reject);
        try {
            let buff = socket.read(numberOfBytes);
            if (null === buff) {
                socket.once('readable', function () {
                    readSocket(socket, numberOfBytes).then((b) => {
                        completed(null, b);
                    }, (err) => {
                        completed(err);
                    });
                });
            }
            else {
                completed(null, buff);
            }
        }
        catch (e) {
            completed(e);
        }
    });
}
920392
def recv(sock, size):
    """"""
    data = sock.recv(size, socket.MSG_WAITALL)
    if len(data) < size:
        raise socket.error(ECONNRESET, 'Connection closed')
    return data
1296474
def read(self, size=None):
        
        data = self.rfile.read(size)
        self.bytes_read += len(data)
        self._check_length()
        return data
735366
def _net_read(sock, count, expiration):
    
    s = ''
    while count > 0:
        _wait_for_readable(sock, expiration)
        n = sock.recv(count)
        if n == '':
            raise EOFError
        count = count - len(n)
        s = s + n
    return s
439436
def ber_from_socket(s):
    
    if isinstance(s, network.SocketClient):
        recv = s.receive
    else:
        recv = s.recv
    data = recv(1)

    length = data[0]
    bytes_read = 1
    if length > 127:
        bytes_read += length & 127 # Strip off the high bit
        data += recv(bytes_read - 1)
        length = 0
        for i in range(1, bytes_read):
            length += data[i] << (8 * (bytes_read - i - 1))
    return length, bytes_read, data
660826
def random_bytes(n):
    

    n = min(n, 100 * 1024)  # set 100KB limit

    params = CaseInsensitiveDict(request.args.items())
    if "seed" in params:
        random.seed(int(params["seed"]))

    response = make_response()

    # Note: can't just use os.urandom here because it ignores the seed
    response.data = bytearray(random.randint(0, 255) for i in range(n))
    response.content_type = "application/octet-stream"
    return response
291461
def receive(self, siz):
        
        result = bytearray()
        data = 'x'
        while len(data) > 0:
            data = self.sock.recv(siz - len(result))
            result += data
            if len(result) == siz:
                return result
            if len(result) > siz:
                raise Exception('Received more bytes than expected')
        raise Exception('Error receiving data. %d bytes received'%len(result))
204064
def recv(self, size):
        """"""
        while True:
            try:
                data = self._sock.recv(size)
                self.bytes_read += len(data)
                return data
            except socket.error as e:
                what = (
                    e.args[0] not in errors.socket_errors_nonblocking
                    and e.args[0] not in errors.socket_error_eintr
                )
                if what:
                    raise
1029550
def readBytes(self, size):
        

        # try to satisfy the read from any buffered data
        if self._iobuf:
            if size >= len(self._iobuf):
                res = self._iobuf
                self.buf = None
                return res
            res = self._iobuf[:size]
            self._iobuf = self._iobuf[size:]
            return res

        # We need to initiate a read
        buf = ctypes.create_string_buffer(size)
        olap = OVERLAPPED()
        olap.hEvent = self._waitable

        log("made read buff of size %d", size)

        # ReadFile docs warn against sending in the nread parameter for async
        # operations, so we always collect it via GetOverlappedResultEx
        immediate = ReadFile(self.pipe, buf, size, None, olap)

        if not immediate:
            err = GetLastError()
            if err != ERROR_IO_PENDING:
                self._raise_win_err("failed to read %d bytes" % size, err)

        nread = wintypes.DWORD()
        if not self._get_overlapped_result_ex(
            self.pipe, olap, nread, 0 if immediate else self.timeout, True
        ):
            err = GetLastError()
            CancelIoEx(self.pipe, olap)

            if err == WAIT_TIMEOUT:
                log("GetOverlappedResultEx timedout")
                raise SocketTimeout(
                    "timed out after waiting %dms for read" % self.timeout
                )

            log("GetOverlappedResultEx reports error %d", err)
            self._raise_win_err("error while waiting for read", err)

        nread = nread.value
        if nread == 0:
            # Docs say that named pipes return 0 byte when the other end did
            # a zero byte write.  Since we don't ever do that, the only
            # other way this shows up is if the client has gotten in a weird
            # state, so let's bail out
            CancelIoEx(self.pipe, olap)
            raise IOError("Async read yielded 0 bytes; unpossible!")

        # Holds precisely the bytes that we read from the prior request
        buf = buf[:nread]

        returned_size = min(nread, size)
        if returned_size == nread:
            return buf

        # keep any left-overs around for a later read to consume
        self._iobuf = buf[returned_size:]
        return buf[:returned_size]