您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“如何使用libevent寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何使用libevent寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器”這篇文章吧。
示例代碼
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <event.h> 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)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。