Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python socket and measuing bytes received

All,

I have a simple Python script that sends 4 bytes of data to a service and sets a 1024 recv buffer. I am trying to figure out how to measure the number of bytes returned from the service to put in some logic. So if the response is greater than 10 bytes do X, else do Y. I just cant figure out how to measure the response in bytes. Pointers would be greatly appreciated.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ("10.0.0.1", 5000)
s.connect(address)
s.send('1234')
data = socket.recv(1024)
s.close()
like image 363
Christoph Avatar asked Nov 20 '25 19:11

Christoph


1 Answers

size = len(data)

data is a block of bytes represented as a string - so getting the length of the string will give you what you want.

The problem you'll run into though is that you're using TCP which is a stream - there's no guarantee that you'll get (only) one whole, complete message on a recv(). An easy way around that is to add a size parameter to your protocol and add logic to reassemble & deserialize messages.

like image 144
Jeremy Brown Avatar answered Nov 23 '25 10:11

Jeremy Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!