Question

i need to send 1 int und 1 bytearray(200) through a socket to a server. The socket.send() function only accpets exactly one string so i need the int and bytearray as bytes in one String. I tryed to convert both to a string with struct.pack(), which is working well for the int but not for the bytearray.

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    print "Connected to: ",  s.getpeername()
    #Trying to put int and bytearray into 1 string
    a= 02 # int
    b= bytearray(200) #bytearray
    c = struct.pack("B", a)
    c += b



    s.send(c)
    print s.recv(1024)
Was it helpful?

Solution

Concatenate them:

>>> import struct
>>> struct.pack('<l', 1234) + bytearray([0]*10)
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

or also specify the bytearray:

>>> struct.pack('<l10s', 1234, bytearray([0]*10)) # In Python 3.x
# struct.pack('<l10s', 1234, bytes(bytearray([0]*10))) # In Python 2.x
b'\xd2\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top