Hare by Example: UDP Server

Hare can also be used to write a UDP server to accept incoming connections and data. Here, we have just a simple echo server that will read incoming data and send it back to the client that sent it.

use fmt;
use net::udp;
use net::ip;
use os;
use strings;

export fn main() void = {
	// Create a udp listener on the local v4 ip and a port
	const listener = udp::listen(ip::LOCAL_V4, 9000)!;

	// Since we're writing a server we loop forever to wait for
	// incoming connections and data.
	for (true) {
		// We define a buffer to hold incoming data
		let buf: [os::BUFSZ]u8 = [0...];

		// Next we define an address and port to hold source of
		// the incoming connection and data.
		let src: ip::addr = ip::ANY_V4;
		let port: u16 = 0;

		// Block and wait for incoming data on the listener and
		// write the buf, src, port accordingly.
		const sz = udp::recvfrom(listener, &buf, &src, &port)!;

		// Re-slice the buffer to the length of the data that
		// came in.
		let buf = buf[..sz];

		fmt::printfln("{}:{} says {}", ip::string(src), port,
			strings::fromutf8_unsafe(buf))!;

		// Echo it back to the client
		udp::sendto(listener, buf, src, port)!;
	};
};
# First, run the example to start the UDP server
$ hare run udp-server.ha
127.0.0.1:56971 says Hello UDP server! I am a UDP client!

# Second, use netcat to send data to our server. Once we type the first
# line of text it will get echoed back to us.
$ nc -u 0.0.0.0 9000
Hello UDP server! I am a UDP client!
Hello UDP server! I am a UDP client!