Hare by Example: UDP Client

Hare gives us direct access to sockets and so lets look at making a UDP client to send some data.

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

export fn main() void = {
	// Parse an IP address into an ip::addr so we can connect to it.
	const addr = ip::parse("0.0.0.0")!;

	// Create a udp connection to that address and port
	const conn = udp::connect(ip::LOCAL_V4, 9000)!;

	// Create a message to send over the connection.
	const msg = strings::toutf8("Hello, from UDP Hare client!");

	// Finally, send the message using the connection.
	const sz = udp::send(conn, msg)!;
	fmt::printf("Sent {} bytes\n", sz)!;
};
# First, start netcat in one terminal listening on port 9000
$ nc -lu -p 9000
Hello, from UDP Hare client!

# Second, run example in another terminal
$ hare run udp-client.ha
Send 28 bytes