Search code examples
socketsudpdudpclient

D language: UDP client does not receive reply


I have created a toy example for a UDP echo client and server. However, I do not receive the reply from the server and I wonder what am I doing wrong.

Client:

#!/usr/bin.rdmd
import std.stdio;
import std.socket;
import std.string;
import std.conv;
import std.random;
import std.outbuffer;

int main(string[] args) {
  if (args.length != 3) {
    writefln("usage: %s <server host> <port>",args[0]); 
    return 0;
  }

  auto s = new UdpSocket();

  auto addr = new InternetAddress(args[1], to!ushort(args[2]));
  s.connect(addr);
  scope(exit) s.close();

  for (int i = 0; i < 1000; i++){
    auto r = uniform(int.min,int.max);
    auto send_buf = new OutBuffer();

    send_buf.write(r);

    s.send(send_buf.toBytes());

    ubyte[r.sizeof] recv_buf;
    s.receive(recv_buf);

    assert(r == *cast(int*)(send_buf.toBytes().ptr));
  }



  return 0;
}

Server:

#!/usr/bin.rdmd
import std.stdio;
import std.socket;
import std.string;
import std.conv;

int main(string[] args) {
  if (args.length != 2) {
    writefln("usage: %s <port>",args[0]); 
    return 0;
  }

  auto s = new UdpSocket();

  auto addr = new InternetAddress("localhost", to!ushort(args[1]));
  s.bind(addr);

  while (true){
    ubyte[int.sizeof] recv_buf;
    s.receive(recv_buf);

    writefln("Received: %s\n",recv_buf);

    s.send(recv_buf);


  }

  writeln("sent");

  return 0;
}

If you execute the programs you will see that the client hangs in receive, while the server has already sent the reply.

Do you know what am I doing wrong?

BTW, What is the best resource for network programming in D?


Solution

  • The UDP socket on the server is not "connected", so you cannot use send. It probably returned an error message that you didn't check. On the server, use receiveFrom with sendTo to reply to a message.

    Note that while UDP is a connectionless protocol, the socket API supports the concept of a connected UDP socket, which is merely the socket library remembering the target address for when you call send. It will also filter out messages not coming from the connected address when calling receive. Connected sockets are usually a bad fit for UDP server programs.