HomeForumSourceResearchGuide
<< back to How To home

These programs demonstrate how to create a UDP server and a UDP client. The client sends some data to the server, and the server prints the data out.

We start with the server side. Create a new file Server.dn and open it in a text editor. We're going to use the UDPServer interface, the command-line output interface, and the IntUtil interface to help us print integers to the command line. We'll start with this code in our new file:

component provides App requires io.Output out, data.IntUtil iu,
				net.UDPServer udp {

}

The App interface has one function called main. Any runnable component will implement App, indicating it has a main method that Dana can launch.

We now need to implement our App interface, which we'll do like this:

component provides App requires io.Output out, data.IntUtil iu,
				net.UDPServer udp {
	
	int App:main(AppParam params[])
		{
		UDPServer host = new UDPServer()
		host.bind(UDPServer.ANY_ADDRESS, 2012)
		
		while (true)
		   {
		   Datagram dg = host.recv()
		   
		   if (dg != null)
			   {
			   out.print("data: $(dg.content)")
			   out.println("from: $(dg.address):$(dg.port)")
			   }
			}
		
		return 0
		}
	}

This program instantiates a new UDP server socket, and binds it to the local host at port 2012. The ANY_ADDRESS constant means that we'll listen for both IPv4 and IPv6 connections. We then use a loop to accept new datagram packets from clients. We print out the content of each packet, along with the IP address and port of the sender.

Next we'll write the client side. Create a new file Client.dn and open it in a text editor. Here we'll just use the UDPClient interface, and use it to send a message to our server:

component provides App requires net.UDPClient udp {

int App:main(AppParam params[])
	{
	udp.send("127.0.0.1", 2012, new char[](params[0].string, "\n"))
	
	return 0
	}
}

Our client program assumes that we provide a command-line parameter as our data to send.

We can now compile both programs using the Dana compiler. Open a command-prompt in the directory containing your files and type:

dnc Server.dn

dnc Client.dn

Pressing enter after each command. This will compile your components.

We run both programs using Dana's interpreter. We'll now need two different command line windows in the same directory; in the first one we can type:

dana Server

And press enter.

In the other command line window we type:

dana Client hello!

And press enter. You should see your message printed out at the server.

The full list of standard interfaces that you can use in requires directives can be viewed at the Dana API pages along with documentation of each one. In this example we used: