0

I have developed a client and a server using swift nio, I have no problems sending package of all size between 12 and 1000bytes since server sends a pack of 528bytes and when client got it, it is 512bytes. I'm trying to figure out why it happens. Does anyone knows if there is any chance to set a minimum ByteBuffer capacity? or if I'm missing something. Thanks to all.enter image description here

1 Answers1

1

Assuming you're using TCP (that is, using ClientBootstrap), you cannot expect that the boundaries of messages sent by the server will be reflected in your reads. TCP is "stream-oriented": this means that the messages don't have boundaries at all, they behave just like a stream of data. In the NIO case, that means you would expect to see another read shortly after that contains more data.

The initial ByteBuffer capacity used for reads is controlled by the RecvByteBufferAllocator used by the Channel. This can be overridden:

ClientBootstrap(group: group)
    .channelOption(ChannelOptions.recvAllocator, 
                   AdaptiveRecvByteBufferAllocator(minimum: 1024, initial: 1024, maximum: 65536))

The standard defaults for the AdaptiveRecvByteBufferAllocator in NIO 2.23.0 are a minimum size of 64 bytes, an initial size of 1024 bytes, and a maximum size of 65536 bytes. In general we don't recommend overriding these defaults unless you need to: for TCP NIO will ensure the buffer is appropriately sized for the reads we're seeing.

Lukasa
  • 14,599
  • 4
  • 32
  • 34
  • Really grateful for the answer. On first developing I started without using NIO and managing server and client with simple tcp network, to pass problem of maximum tcp package size I used to divide them. So on NIO I could imagine it was something like this but I couldn't find anything online to set bootstrap ByteBuffer size. – Valerio Schips Nov 19 '20 at 12:10
  • If you want to use TCP, you can use length-prefixed framing to delimit your messages. NIO ships some useful helpers: https://github.com/apple/swift-nio-extras/blob/main/Sources/NIOExtras/LengthFieldBasedFrameDecoder.swift, https://github.com/apple/swift-nio-extras/blob/main/Sources/NIOExtras/LengthFieldPrepender.swift – Lukasa Nov 19 '20 at 20:55