vibe-core
vibe-core copied to clipboard
Creating an UDP server is cumbersome
Creating a TCP server is rather straightforward and documented. However, as I tried to create an UDP server, I hit a few issues:
- Low documentation: I could only find https://github.com/vibe-d/vibe.d/blob/1f830a8241041c39c61bbdcde37fe4bc40c13432/examples/udp/source/app.d in Vibe.d
- No way to set up a server mode: listenTCP allows passing a callback. UDP only seems to have
recv
, which will throw on timeout.
Additionally, calling listenUDP
before the event loop is running results in an invalidHandle
error.
I had the following code:
if (cmdline_args.dns)
{
auto udp = listenUDP(53);
runTask({
while (true) {
auto pack = udp.recv();
logInfo("Got packet: %s", pack);
}
});
}
return runEventLoop();
And got an error. Moving the listenUDP
inside runTask
cleared it.
To be precise, it seems like the UDP handle's validationCounter
stays at 0
while the common
is 1
.
I've tried this recently and it seems to be working properly now.
you shoud use listenUDP on run Task. like this:
if (cmdline_args.dns)
{
runTask({
auto udp = listenUDP(53);
ubyte[] buffer = cast(ubyte[]) Mallocator.instance.allocate(2048);
scope(exit) Mallocator.instance.deallocate(cast(void[]) buffer);
while (true) {
auto pack = udp.recv(buffer,null);
logInfo("Got packet: %s", pack);
}
});
}
return runEventLoop();
If the fiber is in the same thread it should not make a difference. Also in this case I think we were saving the listener somewhere so we could shut it down when the user pressed Ctrl+C, so it wasn't actually an option.