#include #include #include struct mysession { session* s; struct mysession* next; struct mysession* prev; }; struct mysession* head = 0; struct mysession* tail = 0; void broadcast(stralloc* msg) { /* we need a copy as send_response truncates messages */ stralloc message = {0}; stralloc_copy(&message, msg); for (struct mysession* ms = head; ms; ms = ms->next) { stralloc_copy(&ms->s->response, &message); send_response(ms->s); } stralloc_free(&message); } void handle_request(session* s) { if (!s->handle) { struct mysession* ms = malloc(sizeof(struct mysession)); if (!ms) { close_session(s); return; // give up } ms->s = s; ms->next = 0; /* put our mysession node at the end of the linear list */ ms->prev = tail; if (tail) { tail->next = ms; } else { head = ms; } tail = ms; s->handle = ms; } // struct mysession* ms = (struct mysession*) s->handle; if (s->request.len == 4 && strncmp(s->request.s, "quit", 4) == 0) { close_session(s); } else { s->response.len = 0; // stralloc_catulong0(&s->response, counter++, 0); broadcast(&s->request); } } void handle_hangup(session* s) { // remove ourself from the list if (s->handle) { struct mysession* ms = s->handle; if (ms->next) { ms->next->prev = ms->prev; } else { tail = ms->prev; } if (ms->prev) { ms->prev->next = ms->next; } else { head = ms->next; } free(ms); s->handle = 0; } } int main() { run_mpx_service(6671, handle_request, handle_hangup); }