-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_client.c
115 lines (101 loc) · 2.25 KB
/
tcp_client.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
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/un.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/epoll.h>
#include <fcntl.h>
#define path "tempfile.socket"
void sig(int sig)
{
char buf[512];
memset(buf, 0, sizeof(buf));
sprintf(buf, "write error, ertrno(%d) -> %s\n", errno, strerror(errno));
write(STDERR_FILENO, buf, strlen(buf));
sleep(3);
exit(-1);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage:./exec [port]\n");
exit(-1);
}
signal(SIGPIPE, sig);
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[1]));
addr.sin_addr.s_addr = inet_addr("192.168.1.115");
connect(sock, (struct sockaddr *)&addr, sizeof(addr));
int old = fcntl(sock, F_GETFL);
int newoption = old | O_NONBLOCK;
fcntl(sock, F_SETFL, newoption);
char buf[512];
memset(buf, 0, sizeof(buf));
int epollfd = epoll_create(5);
epoll_event event[128];
epoll_event e1,e2;
e1.data.fd = sock;
e1.events = EPOLLIN;
epoll_ctl(epollfd, EPOLL_CTL_ADD, sock, &e1);
e2.data.fd = STDIN_FILENO;
e2.events = EPOLLIN;
epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &e2);
int nR;
int ret;
while (1)
{
int number = epoll_wait(epollfd, event, 128, -1);
if (number <= 0)
{
printf("epoll_wait error\n");
break;
}
for (int i = 0; i < number; ++i)
{
if (event[i].data.fd == sock && (event[i].events & EPOLLIN))
{
memset(buf, 0, sizeof(buf));
nR = read(sock, buf, 512);
if (nR == 0)
{
close(sock);
break;
}
write(STDOUT_FILENO, buf, nR);
}
else if (event[i].data.fd == STDIN_FILENO && (event[i].events & EPOLLIN))
{
printf("please input string:");
fflush(stdout);
memset(buf, 0, sizeof(buf));
nR = read(STDIN_FILENO, buf, 512);
if (nR <= 0)
{
printf("errno[%d]:%s\n", errno, strerror(errno));
}
ret = write(sock, buf, nR);
if (ret == 0 && errno == EINTR)
{
printf("write sock error\n");
exit(-1);
}
else if (ret < 0)
{
printf("write sock ret < 0\n");
exit(-1);
}
}
}
}
close(sock);
return 0;
}