-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.cpp
134 lines (116 loc) · 2.31 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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*************************************************************************
> File Name: client.cpp
> Author: Ukey
> Mail: [email protected]
> Created Time: 2017年02月11日 星期六 22时08分46秒
************************************************************************/
#include "utility.h"
int main(int argc, char *argv[])
{
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr.s_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("sock error");
exit(-1);
}
if(connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 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);
}
static struct epoll_event events[2];
addfd(epfd, sock, true);
addfd(epfd, pipe_fd[0], true);
bool is_clientwork = 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(is_clientwork)
{
bzero(&message, BUF_SIZE);
fgets(message, BUF_SIZE, stdin);
if(strncasecmp(message, EXIT, strlen(EXIT)) == 0)
{
is_clientwork = 0;
}
else
{
if(write(pipe_fd[1], message, strlen(message) - 1) < 0)
{
perror("fork error");
exit(-1);
}
}
}
}
else
{
close(pipe_fd[1]);
while(is_clientwork)
{
int epoll_event_count = epoll_wait(epfd, events, 2, -1);
for(int i = 0; i < epoll_event_count; i++)
{
bzero(&message, BUF_SIZE);
if(events[i].data.fd == sock)
{
int ret = recv(sock, message, BUF_SIZE, 0);
if(ret == 0)
{
printf("Server closed connection: %d\n", sock);
close(sock);
is_clientwork = 0;
}
else
printf("%s\n", message);
}
else
{
int ret = read(events[i].data.fd, message, BUF_SIZE);
if(ret == 0)
{
is_clientwork = 0;
}
else
{
send(sock, message, BUF_SIZE, 0);
}
}
}
}
}
if(pid)
{
close(pipe_fd[0]);
close(sock);
}
else
{
close(pipe_fd[1]);
}
return 0;
}