When I run the following python example code,
tick = 0
while True:
tick += 1
print tick
data = s.recv(1024)
if (tick == 1) and data:
print 'from client: %s' %(data)
elif (tick == 2) and data:
print 'from client: %s' %(data)
I see,
1
from client: client msg
2
from client: ?
3
My intuition tells me the 2nd call to s.recv() actually returns some data. And I am fairly certain the client is not sending the `?' character.
So I modify the code hoping to print the first byte of `data',
elif (tick == 2) and data:
print 'from client: %s' %(data)
print struct.unpack("!B", data)
But then I get a traceback stating: "struct.error: unpack requires a string argument of length 1."
The struct package seems to be the standard way of handling socket data. However, this situation seems odd. I am receiving data visually by printing and seeing a "?" and the code also has an "and data" in the conditional but I cannot unpack.
Is there a different way to handle binary data off a socket?
3 Answers 3
elif (tick == 2) and data:
print 'from client: %r' % data # (note 1)
print struct.unpack("!B", data[0]) # (note 2)
- Print the representation like Ignacio suggested.
- You want to unpak one byte, so give
struct.unpackone byte.
Comments
You can view a raw representation of an object by calling repr() or by using the %r formatting specifier.
1 Comment
It sounds like you are trying to interpret the received data without being sure what the received data represents. You can send ascii, or utf-8 encoded unicode or binary data (integers or a jpg or a movie) over a socket. Your receive function needs to be tailored to what was sent.
If you know it is binary, are you just sending bytes? Because that is all of unpack("!B",data[0]) (as suggested by TZ...) will give you. If so, I believe that answer is correct.
You should be able to use len(data) to figure out how much was received, and you should make sure that you check if you have a partial read (trying to send 1025 bytes and only receiving 1024).