Loop to process data packets
972130
function eventLoop()
    {
        // Socket not connected at all?
        if($this->socket == null) {
            return;
        }

        // Server closed connection?
        if(feof($this->socket)) {
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
            $this->socket = null;
            return;
        }

        // See if there's data waiting?
        $byte = $this->readBytes(1, true);
        if(strlen($byte) > 0) {
            $cmd = ord($byte);

            // Read the length of packet..
            $bytes=0;
            $multiplier=1;

            do {
                $t_byte = ord($this->readBytes(1,true));
                $bytes+=($t_byte & 127)*$multiplier;
                $multiplier*=128;

                if($multiplier>128*128*128) {
                    break;
                }
            } while( ($t_byte&128) != 0);

            //
            $payload = "";
            if($bytes>0)
                $payload = $this->readBytes($bytes, false);

            switch( $cmd & 0xf0 ) {
                case 0xd0:      // PINGRESP
                    $this->debugMessage("Ping response received");
                    break;

                case 0x30:      // PUBLISH
                    $msg_qos = ( $cmd & 0x06 ) >> 1; // QoS = bits 1 & 2
                    $this->processMessage( $payload, $msg_qos );
                    break;

                case 0x40:      // PUBACK
                    $msg_qos = ( $cmd & 0x06 ) >> 1; // QoS = bits 1 & 2
                    $this->processPubAck( $payload, $msg_qos );
                    break;
            }

            $this->timeSincePingReq = time();
            $this->timeSincePingResp = time();
        }

        if( $this->timeSincePingReq < (time() - $this->keepAlive ) ) {
            $this->debugMessage("Nothing received for a while, pinging..");
            $this->sendPing();
        }


        if( $this->timeSincePingResp < (time() - ($this->keepAlive*2)) ) {
            $this->debugMessage("Not seen a package in a while, reconnecting..");
            stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
            $this->socket = null;
        }

    }
42898
def sendDAT(self):
        """"""
        finished = False
        blocknumber = self.context.next_block
        # Test hook
        if DELAY_BLOCK and DELAY_BLOCK == blocknumber:
            import time
            log.debug("Deliberately delaying 10 seconds...")
            time.sleep(10)
        dat = None
        blksize = self.context.getBlocksize()
        buffer = self.context.fileobj.read(blksize)
        log.debug("Read %d bytes into buffer", len(buffer))
        if len(buffer) < blksize:
            log.info("Reached EOF on file %s"
                % self.context.file_to_transfer)
            finished = True
        dat = TftpPacketDAT()
        dat.data = buffer
        dat.blocknumber = blocknumber
        self.context.metrics.bytes += len(dat.data)
        log.debug("Sending DAT packet %d", dat.blocknumber)
        self.context.sock.sendto(dat.encode().buffer,
                                 (self.context.host, self.context.tidport))
        if self.context.packethook:
            self.context.packethook(dat)
        self.context.last_pkt = dat
        return finished
1018316
def (self):
        """"""

        archive_data = {"packets": self.recv_msgs,
                        "dataset": self.dataset_name,
                        "num_packets": len(self.recv_msgs),
                        "created": rnow()}
        self.write_to_file(archive_data,
                           self.archive_file)
450756
def _recv_loop(self):
        """"""
        self._completed_response_lines = []
        self._is_multiline = None
        lines_iterator = self._get_lines()
        while True:
            try:
                line = next(lines_iterator)
                if self._is_multiline is None:
                    self._is_multiline = line.startswith("!") or line == "."
                if line.startswith("ERR"):
                    self._respond(ValueError(line))
                elif self._is_multiline:
                    if line == ".":
                        self._respond(self._completed_response_lines)
                    else:
                        assert line[0] == "!", \
                            "Multiline response {} doesn't start with !" \
                            .format(repr(line))
                        self._completed_response_lines.append(line[1:])
                else:
                    self._respond(line)
            except StopIteration:
                return
            except Exception:
                log.exception("Exception receiving message")
                raise
559011
def data_received(self, data):
        """"""
        data = data.decode()
        log.debug('received data: %s', data.strip())
        self.buffer += data
        self.handle_lines()
1271103
def handle_lines(self):
        """"""
        while "\r\n" in self.buffer:
            line, self.buffer = self.buffer.split("\r\n", 1)
            if valid_packet(line):
                self.handle_raw_packet(line)
            else:
                log.warning('dropping invalid data: %s', line)
419687
public void loop() throws IOException
	{
		final long start = System.currentTimeMillis();

		final byte[] buf = new byte[maxRcvBuf];
		try {
			if (timeout > 0)
				s.setSoTimeout(timeout);
			while (!quit) {
				if (total > 0) {
					final long now = System.currentTimeMillis();
					int to = (int) (start + total - now);
					if (to <= 0)
						break;
					// query socket timeout directly from socket since subtypes might
					// have modified the timeout during looping
					final int sto = s.getSoTimeout();
					if (sto > 0)
						to = Math.min(to, sto);
					s.setSoTimeout(to);
				}
				try {
					final DatagramPacket p = new DatagramPacket(buf, buf.length);
					s.receive(p);
					final byte[] data = p.getData();
					onReceive((InetSocketAddress) p.getSocketAddress(), data, p.getOffset(), p.getLength());
				}
				catch (final SocketTimeoutException e) {
					if (total == 0 || start + total > System.currentTimeMillis())
						onTimeout();
				}
				catch (final IOException e) {
					if (!reboundSocket)
						throw e;
					reboundSocket = false;
				}
			}
		}
		catch (final InterruptedIOException e) {
			Thread.currentThread().interrupt();
		}
		catch (final IOException e) {
			if (!quit)
				throw e;
		}
		finally {
			quit();
		}
	}
554703
def feed(self, data):
        
        self.buffer += data
        while len(self.buffer) >= 6:
            self.next_packet()
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)
387048
def write_packets(self):
        """"""
        while self.running:
            if len(self.write_queue) > 0:
                self.write_queue[0].send(self.client)
                self.write_queue.pop(0)
810371
def _parse(self):
        
        timestamp = 0
        invalid = False
        while True:
            byte = yield
            hdr = byte
            
            # Sync packet.
            if hdr == 0:
                packets = 0
                while True:
                    # Check for final 1 bit after at least 5 all-zero sync packets
                    if (packets >= 5) and (byte == 0x80):
                        break
                    elif byte == 0:
                        packets += 1
                    else:
                        # Get early non-zero packet, reset sync packet counter.
                        #packets = 0
                        invalid = True
                        break
                    byte = yield
                self._itm_page = 0
            # Overflow packet.
            elif hdr == 0x70:
                self._send_event(events.TraceOverflow(timestamp))
            # Protocol packet.
            elif (hdr & 0x3) == 0:
                c = (hdr >> 7) & 0x1
                d = (hdr >> 4) & 0b111
                # Local timestamp.
                if (hdr & 0xf) == 0 and d not in (0x0, 0x3):
                    ts = 0
                    tc = 0
                    # Local timestamp packet format 1.
                    if c == 1:
                        tc = (hdr >> 4) & 0x3
                        while c == 1:
                            byte = yield
                            ts = (ts << 7) | (byte & 0x7f)
                            c = (byte >> 7) & 0x1
                    # Local timestamp packet format 2.
                    else:
                        ts = (hdr >> 4) & 0x7
                    timestamp += ts
                    self._send_event(events.TraceTimestamp(tc, timestamp))
                # Global timestamp.
                elif hdr in (0b10010100, 0b10110100):
                    t = (hdr >> 5) & 0x1
                    # TODO handle global timestamp
                # Extension.
                elif (hdr & 0x8) == 0x8:
                    sh = (hdr >> 2) & 0x1
                    if c == 0:
                        ex = (hdr >> 4) & 0x7
                    else:
                        ex = 0
                        while c == 1:
                            byte = yield
                            ex = (ex << 7) | (byte & 0x7f)
                            c = (byte >> 7) & 0x1
                    if sh == 0:
                        # Extension packet with sh==0 sets ITM stimulus page.
                        self._itm_page = ex
                    else:
                        #self._send_event(events.TraceEvent("Extension: SH={:d} EX={:#x}\n".format(sh, ex), timestamp))
                        invalid = True
                # Reserved packet.
                else:
                    invalid = True
            # Source packet.
            else:
                ss = hdr & 0x3
                l = 1 << (ss - 1)
                a = (hdr >> 3) & 0x1f
                if l == 1:
                    payload = yield
                elif l == 2:
                    byte1 = yield
                    byte2 = yield
                    payload = (byte1 | 
                                (byte2 << 8))
                else:
                    byte1 = yield
                    byte2 = yield
                    byte3 = yield
                    byte4 = yield
                    payload = (byte1 | 
                                (byte2 << 8) |
                                (byte3 << 16) |
                                (byte4 << 24))
                
                # Instrumentation packet.
                if (hdr & 0x4) == 0:
                    port = (self._itm_page * 32) + a
                    self._send_event(events.TraceITMEvent(port, payload, l, timestamp))
                # Hardware source packets...
                # Event counter
                elif a == 0:
                    self._send_event(events.TraceEventCounter(payload, timestamp))
                # Exception trace
                elif a == 1:
                    exceptionNumber = payload & 0x1ff
                    exceptionName = self._core.exception_number_to_name(exceptionNumber, True)
                    fn = (payload >> 12) & 0x3
                    if 1 <= fn <= 3:
                        self._send_event(events.TraceExceptionEvent(exceptionNumber, exceptionName, fn, timestamp))
                    else:
                        invalid = True
                # Periodic PC
                elif a == 2:                        
                    # A payload of 0 indicates a period PC sleep event.
                    self._send_event(events.TracePeriodicPC(payload, timestamp))
                # Data trace
                elif 8 <= a <= 23:
                    type = (hdr >> 6) & 0x3
                    cmpn = (hdr >> 4) & 0x3
                    bit3 = (hdr >> 3) & 0x1
                    # PC value
                    if type == 0b01 and bit3 == 0:
                        self._send_event(events.TraceDataTraceEvent(cmpn=cmpn, pc=payload, ts=timestamp))
                    # Address
                    elif type == 0b01 and bit3 == 1:
                        self._send_event(events.TraceDataTraceEvent(cmpn=cmpn, addr=payload, ts=timestamp))
                    # Data value
                    elif type == 0b10:
                        self._send_event(events.TraceDataTraceEvent(cmpn=cmpn, value=payload, rnw=(bit3 == 0), sz=l, ts=timestamp))
                    else:
                        invalid = True
                # Invalid DWT 'a' value.
                else:
                    invalid = True
782177
def _read_loop(self):
        
        while self._running:
            received_data_raw = self._receive_all()
            if self._running:
                self.receive_count += 1
                self.datetime_last_received = datetime.datetime.utcnow()
                received_data_split = received_data_raw.split(self.__CRLF)
                for received_data in received_data_split:
                    if received_data:
                        self._data(received_data)
201806
def alloc(self):
        """"""
        byte = 0
        remaining_bytes = bytearray(5)
        i = 0
        
        remaining_length = self.remaining_length
        
        self.payload = None
        self.remaining_count = 0
        loop_flag = True
        
        #self.dump()
        while loop_flag:
            byte = remaining_length % 128
            remaining_length = remaining_length / 128
            
            if remaining_length > 0:
                byte = byte | 0x80
                
            remaining_bytes[self.remaining_count] = byte
            self.remaining_count += 1
            
            if not (remaining_length > 0 and self.remaining_count < 5):
                loop_flag = False
        
        if self.remaining_count == 5:
            return NC.ERR_PAYLOAD_SIZE
        
        self.packet_length = self.remaining_length + 1 + self.remaining_count
        self.payload = bytearray(self.packet_length)
        
        self.payload[0] = self.command
        
        i = 0
        while i < self.remaining_count:
            self.payload[i+1] = remaining_bytes[i]
            i += 1
        
        self.pos = 1 + self.remaining_count
        
        return NC.ERR_SUCCESS
46767
def capture_packet(self):
        '''  '''
        data = self.socket.recv(self._buffer_size)

        for h in self.capture_handlers:
            h['reads'] += 1
            h['data_read'] += len(data)

            d = data
            if 'pre_write_transforms' in h:
                for data_transform in h['pre_write_transforms']:
                    d = data_transform(d)
            h['logger'].write(d)
235782
def receive_data(data)
      #append data to buffer
      @data << data

      while (@data.length >=4)
        cmd_length = @data[0..3].unpack('N').first
        if(@data.length < cmd_length)
          #not complete packet ... break
          break
        end

        pkt = @data.slice!(0,cmd_length)

        begin
          # parse incoming PDU
          pdu = read_pdu(pkt)

          # let subclass process it
          process_pdu(pdu) if pdu
        rescue Exception => e
          logger.error "Error receiving data: #{e}\n#{e.backtrace.join("\n")}"
          run_callback(:data_error, e)
        end

      end
    end
67500
function broadcast(connections, packet) {
    var i = connections.length;
    while (i--) {
        connections[i].write(packet);
        flush(connections[i]);
    }
}
111199
def digest_packets(packets, hasher):
    """"""
    data_to_hash = io.BytesIO()
    for p in packets:
        data_to_hash.write(p['_to_hash'])
    hasher.update(data_to_hash.getvalue())
    return hasher.digest()