UDP Networking

Hi there!

I’m trying to make UDP-Networking work for C++ target.

I’m quite happy with the client code:

var udpSocket:UdpSocket = new UdpSocket();
var clientHost:Host = new Host(Host.localhost());
udpSocket.bind(clientHost, 9332);

var server:Address= new Address();
server.host = new Host(Host.localhost()).ip; //debug on same machine or change ip
server.port = 9331;
message = Bytes.ofString("123456789");
udpSock.sendTo(message, 0, message.length, server);

But for the server I am still searching for a way to know how many bytes I really received:

var udpSocket:UdpSocket = new UdpSocket();
var host:Host = new Host(Host.localhost());
udpSocket.bind(host, 9331);

var receiveBytes:Bytes = Bytes.alloc(2048);
var senderAddress:Address = new Address();
while(true) {
  var funk = udpsocket.readFrom(receiveBytes,0,2048,receiveAddress);
  // do something with receiveBytes, but how much is in there?

Of course one could define a protocol where the server doesn’t need to know this from the networking API but can infer the length from the data (i.e. send an integer with the length of the message first) or from the protocol (all messages must have the same defined length).

But I very much would prefer to just ask the network API how much data it got. I think that should be possible, every packet has a defined length, doesn’t it?

UPDATE: Ahh, that was stupid of me. The int return value is what I was looking for! (Although a little bit more documentation would have been nice)

1 Like