Created
October 3, 2012 18:11
-
-
Save arianvp/3828702 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "server.h" | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <netinet/in.h> | |
#include <fcntl.h> | |
static void io_cb(struct ev_loop *loop, struct ev_io *watcher, int events) | |
{ | |
if (events & EV_WRITE) | |
{ | |
write(watcher->fd, "hey\n", 5); | |
} | |
ev_io_stop(loop, watcher); | |
} | |
static void accept_cb(struct ev_loop *loop, struct ev_io *watcher, int events) | |
{ | |
int sockfd; | |
struct sockaddr_in addr; | |
if (events & EV_ERROR) | |
{ | |
perror("invalid accept event"); | |
return; | |
} | |
socklen_t len = sizeof(addr); | |
sockfd = accept(watcher->fd, (struct sockaddr *)&addr, &len); | |
if(sockfd < 0) | |
{ | |
perror("accept error"); | |
return; | |
} | |
fcntl(sockfd, F_SETFL, O_NONBLOCK); | |
ev_io_init(watcher, io_cb, sockfd, EV_READ | EV_WRITE); | |
ev_io_start(loop, watcher); | |
} | |
static void idle_cb(struct ev_loop *loop, struct ev_idle *watcher, int events) | |
{ | |
//we can haz whats left of the 600ms for other thingies (game content?) | |
} | |
struct server *server_new(short port) | |
{ | |
int sockfd; | |
struct sockaddr_in addr; | |
struct server *server; | |
server = malloc(sizeof(struct server)); | |
if(server == NULL) | |
return NULL; | |
sockfd = socket(PF_INET, SOCK_STREAM, 0); | |
addr.sin_family = AF_INET; | |
addr.sin_port = htons(port); | |
addr.sin_addr.s_addr = INADDR_ANY; | |
if(bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) != 0) | |
{ | |
perror("bind"); | |
abort(); | |
} | |
fcntl(sockfd, F_SETFL, O_NONBLOCK); | |
listen(sockfd,10); | |
ev_io_init(&(server->io_watcher), accept_cb, sockfd, EV_READ); | |
ev_idle_init(&(server->idle_watcher), idle_cb); | |
return server; | |
} | |
void server_start(struct ev_loop *loop, struct server * server) | |
{ | |
ev_io_start(loop, &server->io_watcher); | |
ev_idle_start(loop, &server->idle_watcher); | |
ev_set_io_collect_interval(loop, 0.600); | |
ev_loop(loop, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment