D-language: UDP client does not receive a response

I created a toy example for the echo client and UDP server. However, I am not receiving a response from the server, and I am wondering what I am doing wrong.

Customer:

#!/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 run programs, you will see that the client hangs upon reception, and the server has already sent a response.

Do you know what I am doing wrong?

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

+4
source share
2 answers

The UDP socket on the server is not β€œconnected”, so you cannot use send . It probably returned an error message that you did not check. On the server, use receiveFrom with sendTo to reply to the message.

Note that although UDP is a connectionless protocol, the socket API supports the concept of a connected UDP socket, which is only a socket library that remembers the destination address when you call send . It also filters out messages that do not arrive from the connected address when it receives a call. Connected sockets are generally not well suited for UDP server programs.

+2
source

receive () and receiveFrom () will be blocked by default. This is most likely why it freezes. Send () can also block if the buffer size is not enough. When working with UDP, you must use the sendTo () and receiveFrom () methods.

Moreover, if you want to send some data from the "server" to your "client", then basically both should be encoded as a server and client, and both should know about the address to which they send packets, so you have to reorganize your code with that in mind.

Once upon a time, when I started network programming, the Beej Guide was the best, and I still think so. You should be able to easily transfer C sources from this guide to D.

+1
source

Source: https://habr.com/ru/post/1437836/


All Articles