static void ns_add_connection(NS *ns, int fd) { NS_Connection *conn = calloc(1, sizeof(NS_Connection)); paSet(&ns->connections, fd, conn); P dbgPrint(stderr, "New connection on fd %d\n", fd); disOnData(&ns->dis, fd, ns_handle_data, NULL); }
/* * Open a listen socket on port <port>, address <host> and return its file descriptor. If <port> <= * 0, a random port will be opened (find out which using netLocalPort() on the returned file * descriptor). If <host> is NULL, the socket will listen on all interfaces. Connection requests * will be accepted automatically. Data coming in on the resulting socket will be reported via the * callback installed using nsOnSocket(). */ int nsListen(NS *ns, const char *host, int port) { int listen_fd; if ((listen_fd = tcpListen(host, port)) < 0) { return -1; } disOnData(&ns->dis, listen_fd, ns_accept_connection, NULL); return listen_fd; }
int main(int argc, char *argv[]) { int i; Dispatcher *dis = disCreate(); pipe(fd); disOnData(dis, fd[0], handle_fd0, NULL); disOnTime(dis, nowd() + 0.1, handle_timeout, NULL); for (i = 0; i < fd[0]; i++) { make_sure_that(!disOwnsFd(dis, i)); } make_sure_that(disOwnsFd(dis, fd[0])); disRun(dis); return errors; }
/* * Arrange for <cb> to be called when there is data available on file descriptor <fd>. <cb> will be * called with the given <ns>, <fd> and <udata>, which is a pointer to "user data" that will be * returned <cb> as it was given here, and that will not be accessed by dis in any way. */ void nsOnData(NS *ns, int fd, void (*cb)(NS *ns, int fd, void *udata), const void *udata) { disOnData(&ns->dis, fd, (void(*)(Dispatcher *dis, int fd, void *udata)) cb, udata); }