string - Decoding tcp packets using python -


I am trying to decode the data obtained on a TCP connection. Packets are small, no more than 100 bytes. However, when a lot of them get then I get some packets. Is there a way to prevent this. I am using python

I have tried to isolate the packet, my source starts with packet STX byte and ends with ETX bytes, after bytex, byte packet The length is, (the length of the packet is less than 5) Checksum is the last byte before ETX

  Def decode (data): while true: start = data.find (STX) if start == -1: Message in #no stx pkt = '' data = '' break #stx, next byte is length pktlen = ord ( Eta [1]) is the # Czech Send ending ETX (pktken -1) or checksum invalid if pktlen & lt; 5 or data [pktlen-1]! = ETX or checksum_valid (data [start: pktlen]) == incorrect: print "invalid Pkt" data = data [start + 1:] continue: pkt = data [start: pktlen] data = data [pktlen:] break returns Data, PKT  

I try it this way

  Try the #process reports: except data = sock.recv (256): Continue Other: Data: data, pkt = decode (data) if pkt: process (pkt)  

In addition, if there are many packets in the data stream, then is it best to packet To A collection of Ucion as back lands or just back pack

I'm not familiar with Python, only C, this method is fine. Any advice would be most appreciated. Thanks in advance

thanks

I will create a square that is responsible for decoding Packet from a stream, like this:

  class PacketDecoder (object): STX = ... ETX = ... def __init __ (self): self._stream = '' def feed (Self, buffer): self ._stream + = buffer def decode (self): '' 'Yield packet from the current stream. '' 'While lane (auto ._stream) & gt; 2: end = self._stream.find (self.ETX) if end == -1: break packet_len = ord (self._stream [1]) packet = self._stream [: end] if packet_len & gt; = 5 and check_sum_valid (packet): Use the packet self._stream = self._stream [end + 1:]  

and then use this way:

 < Code> decoder = packet decoder () while correct: data = sock.recv (256) if the data is not there: # handle the lost connection ... decoder for packet in decoder (). Feed (Data): Process (Packet)  

Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -