test.c (3022B)
1 #include <stdint.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 #ifdef _WIN32 7 #include <windows.h> 8 #else 9 #include <unistd.h> 10 #endif 11 12 #include "fnet.h" 13 14 int ticked = 0; 15 16 void onClose(struct fnet_ev *ev) { 17 printf("Connection closed!\n"); 18 fnet_shutdown(); 19 } 20 21 void onData(struct fnet_ev *ev) { 22 printf("Data(%ld): %.*s\n", ev->buffer->len, (int)(ev->buffer->len), ev->buffer->data); 23 24 // Simple echo if it was an accepted connection 25 if (ev->connection->status & FNET_STATUS_ACCEPTED) { 26 fnet_write(ev->connection, ev->buffer); 27 } 28 29 } 30 31 void onConnect(struct fnet_ev *ev) { 32 printf("Connection!!\n"); 33 ev->connection->onData = onData; 34 ev->connection->onClose = onClose; 35 } 36 37 void onTick(struct fnet_ev *ev) { 38 char *data = "Hello world!"; 39 int cnt = *((int*)ev->udata); 40 41 fnet_write(ev->connection, &((struct buf){ 42 .len = strlen(data) + 1, 43 .data = data, 44 })); 45 46 cnt++; 47 *((int*)ev->udata) = cnt; 48 if (cnt >= 4) { 49 fnet_close(ev->connection); 50 exit(0); 51 } 52 } 53 54 int main(int argc, const char *argv[]) { 55 int i, n, cnt = 0; 56 57 const char *addr = "127.0.0.1"; 58 uint16_t port = 1337; 59 int mode = 3; // 1 = listen, 2 = connect 60 61 for( i = 0 ; i < argc ; i++ ) { 62 63 if ( 64 (!strcmp("--address", argv[i])) || 65 (!strcmp("-a", argv[i])) 66 ) { 67 i++; 68 addr = argv[i]; 69 continue; 70 } 71 72 if ( 73 (!strcmp("--port", argv[i])) || 74 (!strcmp("-p", argv[i])) 75 ) { 76 i++; 77 n = atoi(argv[i]); 78 // Must be positive, 0 = not allowed, see TCP spec 79 if (n <= 0) { 80 fprintf(stderr, "%s: Port must be above 1, got %d\n", argv[0], n); 81 return 1; 82 } 83 // Don't allow dynamic ports 84 if (n >= 49152) { 85 fprintf(stderr, "%s: Port must be below 49152, got %d\n", argv[0], n); 86 return 1; 87 } 88 port = n; 89 continue; 90 } 91 92 if ( 93 (!strcmp("--listen", argv[i])) || 94 (!strcmp("-l", argv[i])) 95 ) { 96 mode = 1; 97 continue; 98 } 99 100 if ( 101 (!strcmp("--connect", argv[i])) || 102 (!strcmp("-c", argv[i])) 103 ) { 104 mode = 2; 105 continue; 106 } 107 108 printf("Arg: %s\n", argv[i]); 109 } 110 111 printf("Address: %s\n", addr); 112 printf("Port : %d\n", port); 113 printf("Mode : %s\n", (mode == 1 ? "Listen" : (mode == 2 ? "Connect" : "Unknown"))); 114 115 116 if (mode == 1) { 117 fnet_listen(addr, port, &((struct fnet_options_t){ 118 .proto = FNET_PROTO_TCP, 119 .flags = 0, 120 .onConnect = onConnect, 121 .onData = NULL, 122 .onTick = NULL, 123 .onClose = NULL, 124 .udata = NULL, 125 })); 126 fnet_main(); 127 return 0; 128 } 129 130 if (mode == 2) { 131 fnet_connect(addr, port, &((struct fnet_options_t){ 132 .proto = FNET_PROTO_TCP, 133 .flags = 0, 134 .onConnect = onConnect, 135 .onData = onData, 136 .onTick = onTick, 137 .onClose = onClose, 138 .udata = &cnt, 139 })); 140 fnet_main(); 141 return 0; 142 } 143 144 fprintf(stderr, "Mode not implemented, use --listen or --connect\n"); 145 return 42; 146 }