softpapa建議使用的libevent真的很好用,callback明確簡單,程式寫起來不複雜,libevent我看到國內已經有人幫它寫了三篇教學文章,都相當不錯,我想以後碰到socket programming乾脆就用這套打死算了
小弟簡單用libevent比照此網誌寫了簡單的web server,並做apache benchmark,真機車,libevent效能夠可怕,數據如下
[libevent]
50個人同時連線的情況下,每秒鐘的Request次數: 251.61 [#/sec] (mean)
50個人裡「平均」每個人感受到的回應時間 : 198.812 [ms] (mean)
小弟程式碼列如下
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/queue.h>
- #include <unistd.h>
- #include <sys/time.h>
- #include <fcntl.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <errno.h>
- #include <event.h>
- #include <sys/socket.h>
- #include <arpa/inet.h>
- #include <netdb.h>
-
- #define WEBMSG "HTTP/1.1 200 OK\r\nContent-Length: 29\r\nConnection: close\r\nContent-Type: text/html\r\n\r\nHello This is libevent server"
-
- static void sock_response(int fd, short event, void *arg)
- {
- char buffer[1500];
-
- struct event *ev = arg;
- read(fd,buffer,1500);
- printf("%s\n",buffer);
- write(fd,WEBMSG,strlen(WEBMSG));
- event_del(ev);
- close(fd);
- }
-
- static void sock_connect(int fd, short event, void *arg)
- {
- struct event *evfifo;
- struct sockaddr_in client;
- int connfd,clnlen;
-
- clnlen=sizeof(client);
- connfd=accept(fd,(struct sockaddr *)&client,&clnlen);
- if (connfd <0)
- {
- perror("accept");
- return;
- }
- evfifo=malloc(sizeof(struct event));
- event_set(evfifo, connfd, EV_READ, sock_response, evfifo);
- event_add(evfifo, NULL);
-
- }
-
- int main(int argc,char *argv[])
- {
- struct event evfifo;
- struct sockaddr_in serv;
- int sockfd;
-
-
- memset(&serv,0,sizeof(serv));
- serv.sin_family=AF_INET;
- serv.sin_addr.s_addr=inet_addr("192.168.15.25");
- serv.sin_port=htons(5050);
-
- sockfd=socket(AF_INET,SOCK_STREAM,0);
- if (sockfd==-1)
- {
- perror("sockfd");
- return 0;
- }
- if (bind(sockfd,(struct sockaddr *)&serv,sizeof(serv))==-1)
- {
- perror("bind");
- return 0;
- }
- if (listen(sockfd,1024)==-1)
- {
- perror("listen");
- return 0;
- }
-
- event_init();
- event_set(&evfifo, sockfd, EV_READ|EV_PERSIST, sock_connect, &evfifo);
-
- event_add(&evfifo, NULL);
-
- event_dispatch();
- close(sockfd);
- }
Regular expression-跟brainfuck差不多的東西 (2009-11-13 15:37)
Reading file in kernel-簡單但實用 (2009-10-13 15:18)
Linux file system for dummies-只花你45分鐘 (2009-08-19 15:40)
OPENSSL-TCP SSL初心者之路 (2009-07-16 15:16)
NAPI與pure interrupt driver的效能比較 (2009-04-29 19:06)
usermode helper-來自kernel的呼喚 (2009-04-21 16:19)
kernel module memory detector-抓出有害的kernel module (2009-03-31 13:50)
kernel space coding-如履薄冰 (2009-03-26 09:52)
readahead與posix_advise-預讀取是萬能靈丹? (2009-03-06 15:54)