這篇文章主要為大家展示了“如何使用libevent寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何使用libevent寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器”這篇文章吧。
創(chuàng)新互聯(lián)公司2013年成立,是專(zhuān)業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元硚口做網(wǎng)站,已為上家服務(wù),為硚口各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話(huà):18982081108
示例代碼
#include#include #include #include #include #include #include #include #include void sock_read(int fd, short event, void *arg) { char buf[255]; int len; struct event *ev = arg; len = recv(fd, buf, sizeof(buf)-1, 0); if (len == -1) { perror("recv error/n"); if (errno != EAGAIN && errno != EINTR) { close(fd); free(ev); } return; } else if (len == 0) { close(fd); fprintf(stderr, "Connection closed/n"); free(ev); return; } buf[len] = '/0'; fprintf(stdout, "Read: %s/n", buf); /* Reschedule this event */ event_add(ev, NULL); } void sock_accept(int fd, short event, void *arg) { struct event *ev = arg; struct sockaddr addr; socklen_t len = sizeof(addr); //由于此結(jié)構(gòu)要長(zhǎng)期使用,所以rev必須動(dòng)態(tài)分配,否則離開(kāi)此函數(shù)后會(huì)自動(dòng)釋放,導(dǎo)致segment fault struct event* rev = (struct event*)malloc(sizeof(*rev)); int s = accept(fd, &addr, &len); if (s == -1) { perror("accept error/n"); return; } fprintf(stdout, "accept socket: %d/n", s); /* Initalize one event */ event_set(rev, s, EV_READ, sock_read, rev); /* Add it to the active events, without a timeout */ event_add(rev, NULL); /* Reschedule this event */ event_add(ev, NULL); } int main (int argc, char **argv) { struct event ev; int fd; struct sockaddr_in addr; fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { perror("socket error/n"); exit(-1); } bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(10000); addr.sin_addr.s_addr = 0; if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("bind error/n"); exit(-1); } if (listen(fd, 5) == -1) { perror("listen error/n"); exit(-1); } /* Initalize the event library */ event_init(); /* Initalize one event */ event_set(&ev, fd, EV_READ, sock_accept, &ev); /* Add it to the active events, without a timeout */ event_add(&ev, NULL); event_dispatch(); return (0); }
以上是“如何使用libevent寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!