#include "algo_skel.h" #define NAIVE_BUFFER 128 struct naive_ctx { char buffer[NAIVE_BUFFER]; int start; int end; }; void free_naive(void* app_ctx) { if (app_ctx != NULL) free(app_ctx); } void on_tcp_co(struct evt_core_ctx* ctx, struct evt_core_cat* cat, int fd) { int conn_sock, err; struct sockaddr in_addr; socklen_t in_len; struct epoll_event current_event; in_len = sizeof(in_addr); //while (1) { conn_sock = accept(fd, &in_addr, &in_len); //if (conn_sock == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) break; if (conn_sock == -1) goto co_error; evt_core_add_fd (ctx, "tcp-data", fd); //} return; co_error: perror("Failed to handle new connection"); exit(EXIT_FAILURE); } void on_tcp_data(struct evt_core_ctx* ctx, struct evt_core_cat* cat, int fd) { struct naive_ctx* app_ctx = (struct naive_ctx*) (cat->app_ctx); app_ctx->end = read(fd, app_ctx->buffer, sizeof(char) * NAIVE_BUFFER); if (app_ctx->end == 0) return; if (app_ctx->end == -1 && errno == EAGAIN) return; if (app_ctx->end == -1) goto co_error; app_ctx->start = write(fd, app_ctx->buffer, app_ctx->end); if (app_ctx->end == -1 && errno == EAGAIN) { printf("Lost data EAGAIN\n"); return; } if (app_ctx->end == -1) goto co_error; if (app_ctx->start != app_ctx->end) { printf("Lost data not everything has been written\n"); return; } return; co_error: perror("Failed to handle read write"); exit(EXIT_FAILURE); } void on_udp_data(struct evt_core_ctx* ctx, struct evt_core_cat* cat, int fd) { } void algo_naive(struct algo_skel* as) { as->on_tcp_data.name = "tcp-data"; as->on_tcp_data.flags = 0; as->on_tcp_data.app_ctx = malloc(sizeof(struct naive_ctx)); as->on_tcp_data.free_app_ctx = free_naive; as->on_tcp_data.cb = on_tcp_data; as->on_tcp_data.socklist = NULL; as->on_tcp_co.name = "tcp-listen"; as->on_tcp_co.flags = 0; as->on_tcp_co.app_ctx = NULL; as->on_tcp_co.free_app_ctx = free_naive; as->on_tcp_co.cb = on_tcp_co; as->on_tcp_co.socklist = NULL; as->on_udp_data.name = "udp-data"; as->on_udp_data.flags = 0; as->on_udp_data.app_ctx = malloc(sizeof(struct naive_ctx)); as->on_udp_data.free_app_ctx = free_naive; as->on_udp_data.cb = on_udp_data; as->on_udp_data.socklist = NULL; if (as->on_tcp_data.app_ctx == NULL || as->on_udp_data.app_ctx == NULL) { fprintf(stderr, "Failed to malloc naive_ctx\n"); exit(EXIT_FAILURE); } }