nbio/udp-echo

Code

main.odin ¶
60 linesSource

1/*
2This example shows a simple UDP server that echos back anything it receives.
3
4You can run this with the netcat utility as the client like so: `nc -u 127.0.0.1 1234`.
5*/
6package main
7
8import "core:fmt"
9import "core:nbio"
10
11main :: proc() {
12	if err := nbio.acquire_thread_event_loop(); err != nil {
13		fmt.eprintln("acquire_thread_event_loop: %v", nbio.error_string(err))
14		return
15	}
16	defer nbio.release_thread_event_loop()
17
18	socket, create_err := nbio.create_socket(.IP4, .UDP)
19	if create_err != nil {
20		fmt.eprintfln("create_socket: %v", nbio.error_string(create_err))
21		return
22	}
23
24	if err := nbio.bind(socket, {nbio.IP4_Loopback, 1234}); err != nil {
25		fmt.eprintfln("bind to 127.0.0.1:1234: %v", nbio.error_string(err))
26		return
27	}
28
29	BUF_LEN :: 1024
30	buf := make([]byte, BUF_LEN)
31	defer delete(buf)
32
33	nbio.recv(socket, {buf}, on_recv)
34
35	on_recv :: proc(op: ^nbio.Operation) {
36		if op.recv.err != nil {
37			fmt.eprintfln("recv: %v", nbio.error_string_recv(op.recv.err))
38			return
39		}
40
41		fmt.eprintfln("received %M from %v", op.recv.received, nbio.endpoint_to_string(op.recv.source))
42
43		nbio.send(op.recv.socket, {op.recv.bufs[0][:op.recv.received]}, on_sent, op.recv.source)
44	}
45
46	on_sent :: proc(op: ^nbio.Operation) {
47		if op.send.err != nil {
48			fmt.eprintfln("send: %v", nbio.error_string_send(op.send.err))
49			return
50		}
51
52		fmt.eprintfln("sent %M to %v", op.send.sent, nbio.endpoint_to_string(op.send.endpoint))
53
54		nbio.recv(op.send.socket, {raw_data(op.send.bufs[0])[:BUF_LEN]}, on_recv)
55	}
56
57	if err := nbio.run(); err != nil {
58		fmt.eprintfln("run: %v", nbio.error_string(err))
59	}
60}

Declarations Used 15