summaryrefslogtreecommitdiff
path: root/examples/echo.c
blob: 1671be780c7b358626d7ad02f86b953dd580a31a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifdef __wasm__
#error Not implemented!
#endif

#include "../reduced_system_layer.c"

enum {
  MODE_RECV = 1,
  MODE_SEND,

  PORT = 42069,
};

void update_and_render_frame(void) {
  //  Do nothing.
}

i32 main(i32 argc, c8 **argv) {
  if (argc < 2) {
    if (argc == 1)
      printf("Usade:  %s recv|send\n", argv[0]);
    return 0;
  }

  i32 mode = 0;

  if (strcmp(argv[1], "recv") == 0)
    mode = MODE_RECV;
  else if (strcmp(argv[1], "send") == 0)
    mode = MODE_SEND;

  if (mode == 0) {
    printf("Usage:  %s recv|send\n", argv[0]);
    return 0;
  }

  static c8 buf[256] = "";

  switch (mode) {
    case MODE_RECV: {
      printf("Receiving UDP messages on port %d\n\n", PORT);

      for (;;) {
        i64 n = network_recv(
          0,
          (IP_Address) {
            .protocol   = IPv4_UDP,
            .port       = PORT,
            .v4_address = { 0, 0, 0, 0 },
          },
          sizeof buf - 1,
          (u8 *) buf,
          NULL,
          NULL
        );

        if (strcmp(buf, "!kill") == 0)
          break;

        if (n > 0) {
          buf[n] = '\0';
          printf("%s\n", buf);
        } else
          suspend_thread_for_milliseconds(10);
      }
    } break;

    case MODE_SEND: {
      printf("Sending UDP messages to 127.0.0.1 on port %d\nEnter a message or !quit\n\n> ", PORT);

      for (;;) {
        if (scanf("%s", buf) == 0)
          continue;

        if (strcmp(buf, "!quit") == 0)
          break;

        network_send(
          0,
          (IP_Address) {
            .protocol   = IPv4_UDP,
            .port       = PORT,
            .v4_address = { 127, 0, 0, 1 },
          },
          strlen(buf),
          (u8 *) buf,
          NULL
        );

        printf("> ");
      }
    } break;

    default:;
  }

  shutdown_all_systems();
  return 0;
}