What is the best approach to process a socket connection where I need var data
to end with a line break
?
I'm using the code below but sometimes the tcp
packets get chunked and it takes a long time to match data.endswith("
")
.
I've also tried other approaches, like saving the last line if it doesn't end with
and append it to data
on the next loop. but this also doesn't work because multiple packets get chunked and the 1st and 2nd part don't match.
I've no control over the other end, it basically sends multiple lines that end in
.
Any suggestion will be welcome, as I don't have much knowledge on socket connections.
def receive_bar_updates(s):
global all_bars
data = ''
buffer_size = 4096
while True:
data += s.recv(buffer_size)
if not data.endswith("
"):
continue
lines = data.split("
")
lines = filter(None, lines)
for line in lines:
if line.startswith("BH") or line.startswith("BC"):
symbol = str(line.split(",")[1])
all_bars[symbol].append(line)
y = Thread(target=proccess_bars, kwargs={'symbol': symbol})
y.start()
data = ""
Example of "normal" data
:
line1
line2
line3
Example of chunked data
:
line1
line2
lin
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…