Ambrase
Ambrase

Reputation: 67

Packing structs together

I have few structs composed with python construct(headers and messages). I can send each of them into tcp socket, but failing to unite them together for sending.

    #!/usr/bin/env python2.7

    import socket
    import sys
    from construct import *
    from construct.lib import *

    Header = Struct(
       "HdrLength" / Int16ul,
       "HdrCount" / Int8ul,
    )

    Message = Struct(
       "Smth" / Int32ul
    )

    hdr = Header.build(dict(HdrLength = messages.Header.sizeof() + Message.sizeof(), HdrCount = 1))
    msg = Message.build(dict(Smth = 32))

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('localhost', 10000)
    sock.bind(server_address)
    sock.listen(1)

How can i pack variable amount of messages together to later send as bytes in socket?

    connection.send(what?)

Thanks

Upvotes: 0

Views: 459

Answers (1)

6502
6502

Reputation: 114539

Construct build returns a bytes instances.

You can concatenate bytes instances exactly like you would do for string, using the binary operator +.

Upvotes: 1

Related Questions