4

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?

marcmagransdeabril
  • 1,445
  • 16
  • 27

2 Answers2

3

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.

jA_cOp
  • 3,275
  • 19
  • 15
1

receive() and receiveFrom() will block by default. That is most likely why it hangs. The send() also may block in the case buffer size is not enough. You should use sendTo() and receiveFrom() methods when dealing with UDP.

Moreover, if you want to send some data from the "server" to your "client", then basically both should be coded as both server and client, and both should know about Address they send packets to, so you will have to refactor your code with this in mind.

Long ago when I started network programming Beej's Guide was the best, and I still think it is. You should be able to easily port C sources from that guide to D.

HeyYO
  • 1,989
  • 17
  • 24
DejanLekic
  • 18,787
  • 4
  • 46
  • 77