-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
72 lines (63 loc) · 1.47 KB
/
server.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <event.h>
#include <stdlib.h>
int socketinit()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(3300);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)) == -1)
return -1;
if(listen(sockfd,10 == -1))
return -1;
return sockfd;
}
void recvfun(int fd,short event,void *arg)
{
char buff[128]= {0};
struct event *e = (struct event *)arg;
int n = recv(fd,buff,128,0);
if(n>0)
printf("%s\n",buff);
else if(n == 0)
{
printf("%d dsiconnected\n",fd);
close(fd);
}
else
perror("recv error");
}
void acceptfun(int fd,short event,void *arg)
{
struct event_base *eb = (struct event_base*)arg;
struct sockaddr_in caddr;
int len = sizeof(caddr);
int c = accept(fd,(struct sockaddr*)&caddr,&len);
printf("%d connetc\n",c);
struct event *e = event_new(eb,c,EV_READ|EV_PERSIST,recvfun,e);
event_add(e,NULL);
}
int main()
{
int sockfd = socketinit();
if(sockfd == -1)
perror("sockfd error");
assert(sockfd != -1);
struct event_base *eb= event_base_new();
struct event *e= event_new(eb,sockfd,EV_READ|EV_PERSIST,acceptfun,(void *)eb);
event_add(e,NULL);
event_base_dispatch(eb);
event_free(e);
event_base_free(eb);
return 1;
}