-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient2.cc
More file actions
105 lines (94 loc) · 2.38 KB
/
Copy pathclient2.cc
File metadata and controls
105 lines (94 loc) · 2.38 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <string.h>
#include <pthread.h>
#include <sys/wait.h>
void* thread_func(void* args);
int main(int argc, char** argv)
{
if (argc != 2)
{
printf("usage: a.out <IP>\n");
exit(-1);
}
// pthread_attr_t pthread_attr_detach;
// pthread_attr_init(&pthread_attr_detach);
// pthread_attr_setdetachstate(&pthread_attr_detach, PTHREAD_CREATE_DETACHED);
pid_t pid;
for (int i = 0; i < 5; ++i)
{
// 创建子进程
if ((pid = fork()) == 0)
{
// 每个子进程100次链接
for (int j = 0; j < 1000; ++j)
{
// pthread_t tid;
// pthread_create(&tid, &pthread_attr_detach, &thread_func, (void*)argv[1]);
// pthread_create(&tid, NULL, &thread_func, (void*)argv[1]);
printf("NO. %d of process %d is running\n", j, getpid());
thread_func((void*)argv[1]);
}
}
}
while (wait(NULL) > 0)
;
return 0;
}
void* thread_func(void* args)
{
int sockfd;
struct sockaddr_in addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
char* addr_char = (char*)(args);
addr.sin_addr.s_addr = inet_addr(addr_char);
int len = sizeof(addr);
if ((connect(sockfd, (struct sockaddr*)&addr, len)) == -1)
{
perror("connect error");
exit(-1);
}
else
{
printf("connect success\n");
}
char http_request[] =
/*"GET /home/marvin/MyHttp/index.html HTTP1.1\r\n\*/
"GET /root/MyHttp/index.html HTTP1.1\r\n\
Lengh: 8080\r\n\
Date: Fri Mon 2018\r\n\
\r\n\
<html>\n\
sb\n\
</html>"
;
if (write(sockfd, &http_request, sizeof(http_request)) < 0)
{
perror("write error");
exit(-1);
}
printf("write success\n");
char *read_buff = new char[10240];
int in = 0, nread = 0;
while((in = read(sockfd, read_buff + nread, sizeof(read_buff))) > 0)
{
nread += in;
if (nread > 10000)
break;
}
printf("read from server:\n%s", read_buff);
delete[] read_buff;
close(sockfd);
return NULL;
}