-
Notifications
You must be signed in to change notification settings - Fork 0
/
53.echo_EPETserv.c
120 lines (105 loc) · 3.18 KB
/
53.echo_EPETserv.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//
// Created by satellite on 2023-06-04.
//
#include <fcntl.h>
#include "errno.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "arpa/inet.h"
#include "sys/socket.h"
#include "sys/epoll.h"
#define BUF_SIZE 4
#define EPOLL_SIZE 50
void setnoblock(int fd);
void error_handling(char * message);
int main(int argc , char * argv[])
{
int serv_sock , clnt_sock;
struct sockaddr_in serv_adr , clnt_adr;
socklen_t adr_sz;
int str_len , i;
char buf[BUF_SIZE];
struct epoll_event event;
struct epoll_event* ep_events;
int epfd , event_cnt;
if(argc != 2)
{
printf("usage %s : <port>",argv[0]);
exit(1);
}
serv_sock = socket(PF_INET,SOCK_STREAM,0);
memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
if( bind(serv_sock,(struct sockaddr*)&serv_adr,sizeof(serv_adr)) == -1)
error_handling("bind() error");
if(listen(serv_sock,5) == -1)
error_handling("listen() error");
epfd = epoll_create(EPOLL_SIZE);
ep_events = malloc(sizeof(struct epoll_event) * EPOLL_SIZE);
setnoblock(serv_sock);
event.events = EPOLLIN;
event.data.fd = serv_sock;
epoll_ctl(epfd,EPOLL_CTL_ADD,serv_sock,&event);
printf("..........\n");
while(1)
{
event_cnt = epoll_wait(epfd,ep_events,EPOLL_SIZE,-1);
if(event_cnt == -1)
{
puts("epoll wait...");
break;
}
puts("return epoll_wait");
for(i=0;i<event_cnt;i++)
{
if(ep_events[i].data.fd == serv_sock)
{
adr_sz = sizeof(clnt_adr);
clnt_sock = accept(serv_sock,(struct sockaddr*)&clnt_adr,&adr_sz);
setnoblock(clnt_sock); //将客户端设为非阻塞模式
event.events = EPOLLIN | EPOLLET; //设置注册方式为边缘触发
event.data.fd = clnt_sock;
epoll_ctl(epfd,EPOLL_CTL_ADD,clnt_sock,&event);
printf("connect client : %d \n",clnt_sock);
}
else
{
while(1)
{
str_len = read(ep_events[i].data.fd,buf,BUF_SIZE);
if(str_len == 0)
{
epoll_ctl(epfd,EPOLL_CTL_DEL,clnt_sock,NULL);
close(ep_events[i].data.fd);
printf("closed Client : %d \n",ep_events[i].data.fd);
break;
}
else if(str_len < 0)
{
if(errno == EAGAIN) //意味着缓冲区中的全部数据被读完
break;
}
else
write(ep_events[i].data.fd,buf,str_len);
}
}
}
}
close(serv_sock);
close(epfd);
return 0;
}
void error_handling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
void setnoblock(int fd)
{
int flag = fcntl(fd,F_GETFL,0);
fcntl(fd,F_SETFL,O_NONBLOCK);
}