Python - send uint8 and uint16 to socket -


i'm trying send data python script java server. use socket module in python send , recieve data.

when send data, need specify header datalength in it. header following:

  • a uint8 version number
  • a uint8 padding ('reserved')
  • a uint16 length of data sent

that total of 32 bits.

i can use numpy create array data type, problem sending data through socket. use following function send data:

def send(socket, message):     r = b''      totalsent = 0     # long not has been sent ...     while totalsent < len(message):         # send ; sent = actual sent data         sent = socket.send(message[totalsent:])          r += message[totalsent:]          # nothing sent? -> wrong         if sent == 0:             raise runtimeerror("socket connection broken")          # update total sent         totalsent = totalsent + sent      return r  message = (something_with_numpy(version_number, padding, len(data))) send(socket, message) 

i keep getting typeerrors function. these pop @ len(message), r += message[...], or other place.

i wondering if there better way this, or how fix work?


update: here exact error traces. have tried several different things, these error traces might have become irrelevant.

traceback (most recent call last):   file "quick.py", line 47, in <module>     header += numpy.uint8(version_number) typeerror: ufunc 'add' did not contain loop signature matching types dtype('s3') dtype('s3') dtype('s3')   header = numpy.array([version_number * 255 + padding, len(greetdata)], dtype=numpy.uint16) traceback (most recent call last):   file "quick.py", line 48, in <module>     print(header + greetdata) typeerror: ufunc 'add' did not contain loop signature matching types dtype('s22') dtype('s22') dtype('s22')   traceback (most recent call last):   file "quick.py", line 47, in <module>     r = send(conn, numpy.uint8(version_number))   file "quick.py", line 13, in send     while totalsent < len(message): typeerror: object of type 'numpy.uint8' has no len()   traceback (most recent call last):   file "quick.py", line 47, in <module>     r = send(conn, numpy.array([version_number], dtype=numpy.uint8))   file "quick.py", line 17, in send     r += message[totalsent:] typeerror: ufunc 'add' did not contain loop signature matching types dtype('s3') dtype('s3') dtype('s3') 

you'll want use struct module format header before sending data.

import struct  def send_message(socket, message):     length = len(message)     version = 0  # todo: correct?     reserved = 0  # todo: correct?     header = struct.pack('!bbh', version, reserved, length)     message = header + message  # can use same loop w/ error checking     while ...:         socket.send(...) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -