SENT AS SHORT AS FIRST PACKET AFTER SOCKET CONNECTION
518692
public static OIdentifiable readIdentifiable(final OChannelBinaryClient network) throws IOException {
    final int classId = network.readShort();
    if (classId == RECORD_NULL)
      return null;

    if (classId == RECORD_RID) {
      return network.readRID();
    } else {
      final ORecordInternal<?> record = Orient.instance().getRecordFactoryManager().newInstance(network.readByte());

      if (record instanceof ORecordSchemaAware<?>)
        ((ORecordSchemaAware<?>) record).fill(network.readRID(), network.readInt(), network.readBytes(), false);
      else
        // DISCARD CLASS ID
        record.fill(network.readRID(), network.readInt(), network.readBytes(), false);

      return record;
    }
  }
1129141
def __send_message_recv_reply(self, packed_message):
        
        payload = io.BytesIO()
        try:
            with self._socket_lock:
                self._socket.sendall(packed_message)

                # Read first message header
                raw_header = self._socket.recv(32)
                header = ReplyMessage.header_from_raw_header_data(raw_header)

                # from pyhdb.lib.stringlib import allhexlify
                # print 'Raw msg header:', allhexlify(raw_header)
                msg = 'Message header (32 bytes): sessionid: %d, packetcount: %d, length: %d, size: %d, noofsegm: %d'
                debug(msg, *(header[:5]))

                # Receive complete message payload
                while payload.tell() < header.payload_length:
                    _payload = self._socket.recv(header.payload_length - payload.tell())
                    if not _payload:
                        break   # jump out without any warning??
                    payload.write(_payload)

                debug('Read %d bytes payload from socket', payload.tell())

                # Keep session id of connection up to date
                if self.session_id != header.session_id:
                    self.session_id = header.session_id
                    self.packet_count = -1
        except socket.timeout:
            raise ConnectionTimedOutError()
        except (IOError, OSError) as error:
            raise OperationalError("Lost connection to HANA server (%r)" % error)

        payload.seek(0)  # set pointer position to beginning of buffer
        return ReplyMessage.unpack_reply(header, payload)
1193844
def packet_write(self):
        """"""
        bytes_written = 0
        
        if self.sock == NC.INVALID_SOCKET:
            return NC.ERR_NO_CONN, bytes_written
        
        while len(self.out_packet) > 0:
            pkt = self.out_packet[0]
            write_length, status = nyamuk_net.write(self.sock, pkt.payload)
            if write_length > 0:
                pkt.to_process -= write_length
                pkt.pos += write_length
                
                bytes_written += write_length
                
                if pkt.to_process > 0:
                    return NC.ERR_SUCCESS, bytes_written
            else:
                if status == errno.EAGAIN or status == errno.EWOULDBLOCK:
                    return NC.ERR_SUCCESS, bytes_written
                elif status == errno.ECONNRESET:
                    return NC.ERR_CONN_LOST, bytes_written
                else:
                    return NC.ERR_UNKNOWN, bytes_written
            
            """
            if pkt.command & 0xF6 == NC.CMD_PUBLISH and self.on_publish is not None:
                self.in_callback = True
                self.on_publish(pkt.mid)
                self.in_callback = False
            """
            
            #next
            del self.out_packet[0]
            
            #free data (unnecessary)
            
            self.last_msg_out = time.time()
            
        
        return NC.ERR_SUCCESS, bytes_written
1153555
def ping(payload, &blk)
      send(type: :ping, stream: 0, payload: payload)
      once(:ack, &blk) if blk
    end
48729
def send_packet(self, packet):
        """"""
        data = json.dumps(packet)
        byte = data.encode('utf-8')
        self.udp_socket.sendto(byte, (self._host, self._udp_port))
208178
def send_one_ping(self, current_socket):
        
        # Header is type (8), code (8), checksum (16), id (16), sequence (16)
        checksum = 0

        # Make a dummy header with a 0 checksum.
        header = struct.pack(
            "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number
        )

        padBytes = []
        startVal = 0x42
        for i in range(startVal, startVal + (self.packet_size)):
            padBytes += [(i & 0xff)]  # Keep chars in the 0-255 range
        data = bytes(padBytes)

        # Calculate the checksum on the data and the dummy header.
        checksum = calculate_checksum(header + data) # Checksum is in network order

        # Now that we have the right checksum, we put that in. It's just easier
        # to make up a new header than to stuff it into the dummy.
        header = struct.pack(
            "!BBHHH", ICMP_ECHO, 0, checksum, self.own_id, self.seq_number
        )

        packet = header + data

        send_time = default_timer()

        try:
            current_socket.sendto(packet, (self.destination, 1)) # Port number is irrelevant for ICMP
        except socket.error as e:
            print("General failure (%s)" % (e.args[1]))
            current_socket.close()
            return

        return send_time
1370350
def send_packet(self, dataOut):
        
        try:
            if (pyusb1 is False):
                self.handle.bulkWrite(1, dataOut, 20)
            else:
                self.handle.write(endpoint=1, data=dataOut, timeout=20)
        except usb.USBError:
            pass
331850
async def _send_packet(self, pkt):
        """"""
        if self.state != 'connected':
            return
        await self.queue.put(pkt)
        self.logger.info(
            'Sending packet %s data %s',
            packet.packet_names[pkt.packet_type],
            pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
992023
def mock_server_receive(sock, length):
    """"""
    msg = b''
    while length:
        chunk = sock.recv(length)
        if chunk == b'':
            raise socket.error(errno.ECONNRESET, 'closed')

        length -= len(chunk)
        msg += chunk

    return msg
1334922
def receive(socket, num_bytes=20):
    
    length = int(_receive_all(socket, num_bytes).decode())
    serialized_data = _receive_all(socket, length)
    return pickle.loads(serialized_data)
480451
def receive_data(socket):
    
    answer = b""
    while True:
        packet = socket.recv(4096)
        if not packet: break
        answer += packet
    response = pickle.loads(answer)
    socket.close()
    return response
740127
def send_buffer(self):
        
        buf = self._send_buf
        sock = self.connection._sock
        try:
            timeout = sock.gettimeout()
            sock.setblocking(False)
            try:
                for idx, item in enumerate(buf):
                    sent = 0
                    while 1:
                        try:
                            sent = sock.send(item)
                        except IOError as e:
                            if e.errno == errno.EAGAIN:
                                continue
                            elif e.errno == errno.EWOULDBLOCK:
                                break
                            raise
                        self.sent_something = True
                        break
                    if sent < len(item):
                        buf[:idx + 1] = [item[sent:]]
                        break
                else:
                    del buf[:]
            finally:
                sock.settimeout(timeout)
        except IOError as e:
            self.connection.disconnect()
            if isinstance(e, socket.timeout):
                raise TimeoutError('Timeout writing to socket (host %s)'
                                   % self.host_id)
            raise ConnectionError('Error while writing to socket (host %s): %s'
                                  % (self.host_id, e))
993474
def _recv_loop(self):
        
        required_len = BGP_MIN_MSG_LEN
        conn_lost_reason = "Connection lost as protocol is no longer active"
        try:
            while True:
                next_bytes = self._socket.recv(required_len)
                if len(next_bytes) == 0:
                    conn_lost_reason = 'Peer closed connection'
                    break
                self.data_received(next_bytes)
        except socket.error as err:
            conn_lost_reason = 'Connection to peer lost: %s.' % err
        except bgp.BgpExc as ex:
            conn_lost_reason = 'Connection to peer lost, reason: %s.' % ex
        except Exception as e:
            LOG.debug(traceback.format_exc())
            conn_lost_reason = str(e)
        finally:
            self.connection_lost(conn_lost_reason)
733817
private int sendChunks(ByteBuffer pkt, int maxChunks, OutputStream out) 
                         throws IOException {
    // Sends multiple chunks in one packet with a single write().

    int len = (int) Math.min(endOffset - offset,
                            (((long) bytesPerChecksum) * ((long) maxChunks)));

    // truncate len so that any partial chunks will be sent as a final packet.
    // this is not necessary for correctness, but partial chunks are 
    // ones that may be recomputed and sent via buffer copy, so try to minimize
    // those bytes
    if (len > bytesPerChecksum && len % bytesPerChecksum != 0) {
      len -= len % bytesPerChecksum;
    }

    if (len == 0) {
      return 0;
    }

    int numChunks = (len + bytesPerChecksum - 1)/bytesPerChecksum;
    int packetLen = len + numChunks*checksumSize + 4;
    pkt.clear();

    // The packet format is documented in DFSOuputStream.Packet.getBuffer().
    // Here we need to use the exact packet format since it can be received
    // by both of DFSClient, or BlockReceiver in the case of replication, which
    // uses the same piece of codes as receiving data from DFSOutputStream.
    //

    // write packet header
    pkt.putInt(packetLen);
    if (pktIncludeVersion) {
      pkt.putInt(packetVersion);
    }
    pkt.putLong(offset);
    pkt.putLong(seqno);
    pkt.put((byte)((offset + len >= endOffset) ? 1 : 0));
               //why no ByteBuf.putBoolean()?
    pkt.putInt(len);
    
    int checksumOff = pkt.position();
    byte[] buf = pkt.array();
    
    blockReader.sendChunks(out, buf, offset, checksumOff,
        numChunks, len, crcUpdater, packetVersion);
    
    if (throttler != null) { // rebalancing so throttle
      throttler.throttle(packetLen);
    }
    
    return len;
  }
1308206
def send_data(self):
        """"""
        if not self.connection._sock:
            raise err.InterfaceError("(0, '')")
        conn = self.connection

        try:
            with open(self.filename, 'rb') as open_file:
                packet_size = min(conn.max_allowed_packet, 16*1024)  # 16KB is efficient enough
                while True:
                    chunk = open_file.read(packet_size)
                    if not chunk:
                        break
                    conn.write_packet(chunk)
        except IOError:
            raise err.OperationalError(1017, "Can't find file '{0}'".format(self.filename))
        finally:
            # send the empty packet to signify we are done sending data
            conn.write_packet(b'')
1329578
def send_one_packet(old_packet = nil)
      pf = packet_format
      raise(Errors::NotImplemented, "Unimplemented packet format: #{pf}") unless IMPLEMENTED_FORMATS.include?(pf)

      write('APISPK')

      case pf
      when :list
        read(:expect => /^.*<EOP>$/, :wait => true)
      when :bin48_net_time
        packet = read(:length => 625, :wait => true)
        Packet::Bin48NetTime.read(StringIO.new(packet), old_packet)
      when :bin48_net
        packet = read(:length => 619, :wait => true)
        Packet::Bin48Net.read(StringIO.new(packet), old_packet)
      when :bin48_abs
        packet = read(:length => 379, :wait => true)
        Packet::Bin48Abs.read(StringIO.new(packet), old_packet)
      when :bin32_net
        packet = read(:length => 429, :wait => true)
        Packet::Bin32Net.read(StringIO.new(packet), old_packet)
      when :bin32_abs
        packet = read(:length => 269, :wait => true)
        Packet::Bin32Abs.read(StringIO.new(packet), old_packet)
      end
    end
808170
public void writeEmptyPacket() throws IOException {
    buf[0] = (byte) 4;
    buf[1] = (byte) 0x00;
    buf[2] = (byte) 0x00;
    buf[3] = (byte) this.compressSeqNo++;
    buf[4] = (byte) 0x00;
    buf[5] = (byte) 0x00;
    buf[6] = (byte) 0x00;
    buf[7] = (byte) 0x00;
    buf[8] = (byte) 0x00;
    buf[9] = (byte) 0x00;
    buf[10] = (byte) this.seqNo++;
    out.write(buf, 0, 11);

    if (traceCache != null) {
      traceCache.put(new TraceObject(true, COMPRESSED_PROTOCOL_NOT_COMPRESSED_PACKET,
          Arrays.copyOfRange(buf, 0, 11)));
    }

    if (logger.isTraceEnabled()) {
      logger.trace("send uncompress:{}{}",
          serverThreadLog,
          Utils.hexdump(maxQuerySizeToLog, 0, 11, buf));
    }
  }