-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.cpp
86 lines (79 loc) · 2.47 KB
/
test.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
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <functional>
#include "src/util.h"
#include "src/Buffer.h"
#include "src/InetAddress.h"
#include "src/Socket.h"
#include "src/ThreadPool.h"
using namespace std;
void oneClient(int msgs, int wait){
Socket *sock = new Socket();
InetAddress *addr = new InetAddress("127.0.0.1", 1234);
sock->connect(addr);
int sockfd = sock->getFd();
Buffer *sendBuffer = new Buffer();
Buffer *readBuffer = new Buffer();
sleep(wait);
int count = 0;
while(count < msgs){
sendBuffer->setBuf("I'm client!");
ssize_t write_bytes = write(sockfd, sendBuffer->c_str(), sendBuffer->size());
if(write_bytes == -1){
printf("socket already disconnected, can't write any more!\n");
break;
}
int already_read = 0;
char buf[1024]; //这个buf大小无所谓
while(true){
bzero(&buf, sizeof(buf));
ssize_t read_bytes = read(sockfd, buf, sizeof(buf));
if(read_bytes > 0){
readBuffer->append(buf, read_bytes);
already_read += read_bytes;
} else if(read_bytes == 0){ //EOF
printf("server disconnected!\n");
exit(EXIT_SUCCESS);
}
if(already_read >= sendBuffer->size()){
printf("count: %d, message from server: %s\n", count++, readBuffer->c_str());
break;
}
}
readBuffer->clear();
}
delete addr;
delete sock;
}
int main(int argc, char *argv[]) {
int threads = 100;
int msgs = 100;
int wait = 0;
int o;
const char *optstring = "t:m:w:";
while ((o = getopt(argc, argv, optstring)) != -1) {
switch (o) {
case 't':
threads = stoi(optarg);
break;
case 'm':
msgs = stoi(optarg);
break;
case 'w':
wait = stoi(optarg);
break;
case '?':
printf("error optopt: %c\n", optopt);
printf("error opterr: %d\n", opterr);
break;
}
}
ThreadPool *poll = new ThreadPool(threads);
std::function<void()> func = std::bind(oneClient, msgs, wait);
for(int i = 0; i < threads; ++i){
poll->add(func);
}
delete poll;
return 0;
}