-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.cpp
91 lines (86 loc) · 2.54 KB
/
client.cpp
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
#include "utility.h"
int main(int argc, char *argv[])
{
struct sockaddr_in serverAddr;
serverAddr.sin_family = PF_INET;
serverAddr.sin_port = htons(SERVER_PORT);
serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);
int sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock < 0) {perror("sock error"); exit(-1);}
if(connect(sock, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0)
{
perror("connect error");
exit(-1);
}
int pipe_fd[2];
if(pipe(pipe_fd) < 0) { perror("pipe error"); exit(-1); }
int epfd = epoll_create(EPOLL_SIZE);
if(epfd < 0) { perror("epfd error"); exit(-1); }
addfd(epfd, sock, true);
addfd(epfd, pipe_fd[0], true);
static struct epoll_event events[2];
bool isClientwork = true;
char message[BUF_SIZE];
int pid = fork();
if(pid < 0) { perror("fork error"); exit(-1);}
else if(pid == 0) //子进程
{
//子进程负责写入管道,因此先关闭读端
close(pipe_fd[0]);
printf("Please input 'EXIT' to exit the chat room\n");
while(isClientwork)
{
memset(message, '\0', BUF_SIZE);
fgets(message, BUF_SIZE, stdin);
if(strncasecmp(message, EXIT, strlen(EXIT)) == 0)
isClientwork = 0;
else
{
if(write(pipe_fd[1], message, strlen(message) - 1) < 0)
{
perror("fork error");
exit(-1);
}
}
}
}
else
{
close(pipe_fd[1]);
while(isClientwork)
{
int epoll_events_count = epoll_wait(epfd, events, 2, -1);
for(int i = 0; i < epoll_events_count; i ++)
{
memset(message, '\0', BUF_SIZE);
if(events[i].data.fd == sock)
{
int ret = recv(sock, message, BUF_SIZE, 0);
if(ret == 0)
{
close(sock);
isClientwork = 0;
}
else printf("%s\n", message);
}
else
{
int ret = read(events[i].data.fd, message, BUF_SIZE);
if(ret == 0) isClientwork = 0;
else
send(sock, message, BUF_SIZE, 0);
}
}
}
}
if(pid)
{
close(pipe_fd[0]);
close(sock);
}
else
{
close(pipe_fd[1]);
}
return 0;
}