Reputation: 1532
I'm trying simply send a list of bytes over UDP, with code based on the sample Python sockets module. The client/server transmission works fine with strings. It seemed that using a bytearray was the way to go, however, the length received seems to depend on the content. Sending 1,2,3,4,5,6 works fine, but if I change the 6 to 10 or 11, I only receive 5 bytes on the server. Python 2.7.3 on Ubuntu. What am I not understanding?
Client:
data = bytearray([1,2,3,4,5,6])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(data, (HOST, PORT))
Server:
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print len(data)
idata = map(ord, data)
print len(idata)
print idata[0],idata[1],idata[2],idata[3]
Upvotes: 3
Views: 11956
Reputation: 77367
Don't use strip() - that's for removing whitespace and newlines from strings. In your case, it thought that 10 was whitespace and removed it.
>>> len(bytearray([1,2,3,4,5,10]))
6
>>> len(bytearray([1,2,3,4,5,10]).strip())
5
Upvotes: 2
Reputation: 22914
10 and 11 are ASCII codes for new line and tab, respectively. The strip() call is removing them from data.
Upvotes: 6