README.md (1710B)
1 fnet 2 ==== 3 4 ## Installation 5 6 The easiest way to add fnet to your project is to use [dep][dep] to install it 7 as a dependency, ensure you include lib/.dep/config.mk in your makefile, and add 8 `#include "finwo/fnet.h"` in the files where you're using it. 9 10 ```sh 11 dep add finwo/fnet 12 ``` 13 14 ## Usage 15 16 ### Connect to remote 17 18 ```c 19 #include <string.h> 20 #include "finwo/fnet.h" 21 #include "tidwall/buf.h" 22 23 void onData(struct fnet_ev *ev) { 24 printf("Data received: %s\n", ev->buffer->data); 25 } 26 27 void onTick(struct fnet_ev *ev) { 28 const char *data = "Hello world!"; 29 int cnt = *((int*)ev->udata); 30 31 fnet_write(ev->connection, &((struct buf){ 32 .len = strlen(data) + 1, 33 .data = data, 34 })); 35 36 cnt++; 37 *((int*)ev->udata) = cnt; 38 if (cnt > 10) { 39 fnet_close(ev->connection); 40 exit(0); 41 } 42 } 43 44 int main() { 45 int cnt = 0; 46 47 fnet_connect(addr, port, &((struct fnet_options_t){ 48 .proto = FNET_PROTO_TCP, 49 .flags = 0, 50 .onConnect = NULL, 51 .onData = onData, 52 .onTick = onTick, 53 .onClose = NULL, 54 .udata = &cnt, 55 })); 56 57 fnet_main(); 58 return 0; 59 } 60 ``` 61 62 ### Listen for connections 63 64 ```c 65 #include "finwo/fnet.h" 66 67 // Just an echo 68 void onData(struct fnet_ev *ev) { 69 fnet_write(ev->connection, ev->buffer); 70 } 71 72 // Attach our onData to the connection 73 void onConnect(struct fnet_ev *ev) { 74 ev->connection->onData = onData; 75 } 76 77 int main() { 78 fnet_listen("0.0.0.0", 80, &((struct fnet_options_t){ 79 .proto = FNET_PROTO_TCP, 80 .flags = 0, 81 .onConnect = onConnect, 82 .onData = NULL, 83 .onTick = NULL, 84 .onClose = NULL, 85 .udata = NULL, 86 })); 87 88 fnet_main(); 89 return 0; 90 } 91 ``` 92 93 [dep]: https://github.com/finwo/dep