问题描述
我正在尝试解码通过TCP连接接收到的数据.数据包很小,不超过100个字节.但是,当它们很多时,我会收到一些连接在一起的数据包.有没有办法防止这种情况.我正在使用python
I am trying to decode data received over a tcp connection. The packets are small, no more than 100 bytes. However when there is a lot of them I receive some of the the packets joined together. Is there a way to prevent this. I am using python
我试图分离数据包,我的来源在下面.数据包以STX字节开始,以ETX字节结束,STX之后的字节为数据包长度,(数据包长度小于5无效)校验和是ETX之前的最后一个字节
I have tried to separate the packets, my source is below. The packets start with STX byte and end with ETX bytes, the byte following the STX is the packet length, (packet lengths less than 5 are invalid) the checksum is the last bytes before the ETX
def decode(data):
while True:
start = data.find(STX)
if start == -1: #no stx in message
pkt = ''
data = ''
break
#stx found , next byte is the length
pktlen = ord(data[1])
#check message ends in ETX (pktken -1) or checksum invalid
if pktlen < 5 or data[pktlen-1] != ETX or checksum_valid(data[start:pktlen]) == False:
print "Invalid Pkt"
data = data[start+1:]
continue
else:
pkt = data[start:pktlen]
data = data[pktlen:]
break
return data , pkt
我这样使用它
#process reports
try:
data = sock.recv(256)
except: continue
else:
while data:
data, pkt = decode(data)
if pkt:
process(pkt)
如果数据流中有多个数据包,最好将这些数据包作为列表的集合返回,或者仅返回第一个数据包
Also if there are multiple packets in the data stream, is it best to return the packets as a collection of lists or just return the first packet
我不太熟悉python,只有C,这种方法还可以.任何建议将不胜感激.预先感谢
I am not that familiar with python, only C, is this method OK. Any advice would be most appreciated. Thanks in advance
谢谢
推荐答案
我将创建一个类,负责对来自流的数据包进行解码,如下所示:
I would create a class that is responsible for decoding the packets 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):
'''
Yields packets from the current stream.
'''
while len(self._stream) > 2:
end = self._stream.find(self.ETX)
if end == -1:
break
packet_len = ord(self._stream[1])
packet = self._stream[:end]
if packet_len >= 5 and check_sum_valid(packet):
yield packet
self._stream = self._stream[end+1:]
然后像这样使用:
decoder = PacketDecoder()
while True:
data = sock.recv(256)
if not data:
# handle lost connection...
decoder.feed(data)
for packet in decoder.decode():
process(packet)
这篇关于使用python解码tcp数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!