Search code examples
arrayssocketsudpddynamic-arrays

How can I use a dynamic array for UDP receipt in D?


I would like to create a simple UDP server that can receive messages of varying length. However, it seems as if D's Socket.receiveFrom() expects a static length buffer array. When the following code runs:

void main() {
    UdpSocket       server_s;
    Address         client_addr;
    ubyte[]         in_buf;
    ptrdiff_t       bytesin;

    server_s = new UdpSocket();
    server_s.bind(new InternetAddress(InternetAddress.ADDR_ANY, PORT_NUM));

    bytesin = server_s.receiveFrom(in_buf, client_addr);
    if (bytesin == 0 || bytesin == Socket.ERROR) {
        writeln("Error receiving, bytesin: ", bytesin);
        return;
    }

    // Do stuff
}

receiveFrom() immediately falls through with bytesin == 0. Why is this? Can I even use dynamic arrays for receiving over UDP?


Solution

  • receive and receiveFrom don't do the allocation themselves. You can pass an array of some fixed size big enough to hold any packet you expect, then slice it based on how many bytes you received.

    If you preallocated 64 KB, that ought to fit everything you could conceivably get. I tend to just use 4 KB buffers though.

    ubyte[4096] in_buf;
    bytesin = server_s.receiveFrom(in_buf, client_addr);
    // check for error first then
    auto message_received = in_buf[0 .. bytesin];
    // process it
    // keep looping, reusing the buffer, to get more stuff