Christoph
Christoph

Reputation: 89

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()

Upvotes: 3

Views: 4043

Answers (1)

Jeremy Brown
Jeremy Brown

Reputation: 18318

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.

Upvotes: 3

Related Questions