-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestSend
More file actions
115 lines (94 loc) · 2.67 KB
/
TestSend
File metadata and controls
115 lines (94 loc) · 2.67 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
106
107
108
109
110
111
112
113
114
115
#include <stdint.h>
#include <unistd.h>
#include <thread>
#include <chrono>
#include <atomic>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef int64_t TickCount;
TickCount MyGetTickCount()
{
return std::chrono::steady_clock::now().time_since_epoch().count() / 1000000LL;
}
int startup(int _port,const char* _ip)
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("socket");
exit(1);
}
int opt=1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons( _port);
local.sin_addr.s_addr = inet_addr(_ip);
socklen_t len = sizeof(local);
if(bind(sock,(struct sockaddr*)&local , len) < 0)
{
perror("bind");
exit(2);
}
if(listen(sock, 5) < 0) //允许连接的最大数量为5
{
perror("listen");
exit(3);
}
return sock;
}
int myconnect(int port, const char* ip)
{
int connectfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in target;
target.sin_family = AF_INET;
target.sin_port = htons(port);
target.sin_addr.s_addr = inet_addr(ip);
socklen_t len = sizeof(struct sockaddr_in);
connect(connectfd, (struct sockaddr*)&target, sizeof(target));
return connectfd;
}
int main(int argc, char** argv)
{
int tcount = 0;
if (argc == 1)
tcount = 1;
else
sscanf(argv[1], "%d", &tcount);
int pipes[2];
//pipe2(pipes, 0);
//socketpair(AF_UNIX, SOCK_STREAM, 0, pipes);
std::atomic<int> closeCount{tcount};
int listenfd = startup(10000, "0.0.0.0");
int clientfd = myconnect(10000, "127.0.0.1");
int serverfd = accept(listenfd, NULL, 0);
pipes[0] = clientfd;
pipes[1] = serverfd;
for (int ti = 0; ti < tcount; ++ti)
{
std::thread([pipes, &closeCount]()
{
char buf[4096];
int n = 1000000;
TickCount t0 = MyGetTickCount();
while (n--)
write(pipes[1], buf, 1);
TickCount t1 = MyGetTickCount();
printf("sender %lld~%lld %lld\n", (long long)t0, (long long)t1, (long long)(t1 - t0));
if (std::atomic_fetch_sub(&closeCount, 1) == 1)
close(pipes[1]);
}).detach();
}
{
char tmp[4096] = {};
read(pipes[0], tmp, 4096) > 0;
TickCount t2 = MyGetTickCount();
while (read(pipes[0], tmp, 4096) > 0)
{}
TickCount t3 = MyGetTickCount();
printf("receiver %lld~%lld %lld\n", (long long)t2, (long long)t3, (long long)(t3 - t2));
}
close(pipes[0]);
return 0;
}