0

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

Ambrase
  • 57
  • 1
  • 10
  • Make a working example of your issue, not incomplete pseudocode. Read [mcve]. – Mark Tolonen Aug 18 '17 at 14:22
  • Note TCP is a streaming protocol so there is no need to join them, just send one than the other. – Mark Tolonen Aug 18 '17 at 14:24
  • I want to receive them together as minimal packet. Probably i will need this knowledge of how to unite them for udp too. – Ambrase Aug 18 '17 at 14:27
  • UDP is a message-based protocol, so you will need to merge them together. TCP is not. You could send them one byte at a time. The client must read the header and make sure to read enough bytes for the entire message, so it does not matter if you issue one send for the whole message or one hundred separate sends for one message. – Mark Tolonen Aug 18 '17 at 15:51
  • Due to the Nagle algorithm, multiple separate sends close together will likely be coalesced into one packet for transmission anyway. – Mark Tolonen Aug 18 '17 at 15:54

1 Answers1

1

Construct build returns a bytes instances.

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

6502
  • 112,025
  • 15
  • 165
  • 265