piface / pifacedigital-scratch-handler

Allows Scratch to control PiFace Digital through MESH.
GNU General Public License v3.0
9 stars 5 forks source link

'stream handling' in scratchhandler needs improvement #4

Open heppg opened 10 years ago

heppg commented 10 years ago

In current scratchHandler, the length information is discarded. This leads to lost sync when data are not contained in one chunk of bytes arriving from socket. Here a working sample out of my scratchClient.

while not self.stopped(): try: #

get the bytes from the socket

            # This is not necessarily a full record, just some bytes.
            #
            chunk =  self.scratch_socket.recv(BUFFER_SIZE)
            #
            # no data arriving means: connection closed
            #
            if len(chunk) == 0:
                scratchClient.event_disconnect()
                break
            data += chunk
            #
            # there are multiple records possible in one
            # received chunk
            # ... as well as the data could not be long enough for a full record.
            #
            # need at least 4 bytes to identify length of record.
            #
            while  len(data) >= 4:
                recordLen = (ord(data[0]) << 24) +     \
                            (ord(data[1]) << 16) +     \
                            (ord(data[2]) <<  8) +     \
                            (ord(data[3]) <<  0 )               
                #           
                if recordLen > 512:
                    logger.debug("unusual large record length received: {len:%d}".format(len=recordLen))   
                #
                # are there enough bytes in data for a full record ?
                # if not, leave the loop here and wait for more chunks to arrive.
                #
                if len(data) < 4+recordLen:
                    break   

                record = data[4: 4+recordLen]
                logger.debug( 'data recvd from scratch-Length: %d, Data: %s' , len(record), record)
                self.processRecord ( record )
                #
                # cut off the record from the received data
                #               
                data = data[4+recordLen:]
                #
        except socket.timeout:
            # if logger.isEnabledFor(logging.DEBUG):
            #    logger.debug( "No data received: socket timeout")
            continue
        except Exception as e:
            logger.warn(e)
            scratchClient.event_disconnect()
            self.stop()
            continue