-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
161 lines (130 loc) · 2.41 KB
/
main.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#include "pch.h"
#include "io/sockio.h"
#include "sync/resettable_event.h"
#define PACKET_LEN (1500)
resettable_event<false> ready{ false }, finished{ false };
uint16_t rx_port{ 0 };
ip_protocol_t protocol{ ip_protocol_t::tcp };
tcp_server_t server;
socket_t transmitter, receiver;
void rx();
void tx(uint16_t port);
int main()
{
INIT();
do
{
int t;
printf("Protocol(0: TCP, 1:UDP)? ");
scanf("%d", &t);
if (t == 0)
{
protocol = ip_protocol_t::tcp;
break;
}
else if (t == 1)
{
protocol = ip_protocol_t::udp;
break;
}
} while (true);
std::thread rx_thread{ rx };
ready.wait();
std::thread tx_thread{ tx, rx_port };
printf("press enter to stop... \n");
FLUSH_OUT();
GET_CHAR();
finished.set();
if (protocol == ip_protocol_t::tcp)
{
server.close();
}
transmitter.close();
receiver.close();
tx_thread.join();
rx_thread.join();
FINISH(0);
}
void rx()
{
char packet[PACKET_LEN];
int ret;
if (protocol == ip_protocol_t::tcp)
{
ret = server.create("127.0.0.1");
if (ret != 0)
{
printf("create server failed. error code: %d \n", ret);
return;
}
rx_port = server.port();
ready.set();
ret = server.listen(receiver);
if (ret != 0)
{
if (!finished.is_set())
{
printf("listen failed. error code: %d \n", ret);
}
return;
}
}
else
{
ret = receiver.create(ip_protocol_t::udp, "127.0.0.1");
if (ret != 0)
{
printf("create server failed. error code: %d \n", ret);
return;
}
rx_port = receiver.mine_port();
ready.set();
}
while (!finished.is_set())
{
ret = receiver.recv(packet, PACKET_LEN);
if (ret != 0)
{
if (!finished.is_set())
{
printf("recv failed. error code: %d \n", ret);
}
break;
}
printf("recv %d OK. \n", *(int*)&packet[0]);
}
printf("rx closed. \n");
}
void tx(uint16_t port)
{
char packet[PACKET_LEN];
int cnt;
int ret;
ret = transmitter.create(protocol);
if (ret != 0)
{
printf("create failed. error code: %d \n", ret);
return;
}
ret = transmitter.connect("127.0.0.1", port);
if (ret != 0)
{
printf("connect failed. error code: %d \n", ret);
return;
}
cnt = 0;
while (!finished.wait_for(std::chrono::milliseconds(1500)))
{
printf("\n");
*(int*)&packet[0] = cnt;
ret = transmitter.send(packet, PACKET_LEN);
if (ret != 0)
{
printf("send failed. error code: %d \n", ret);
break;
}
printf("send %d OK. \n", cnt);
++cnt;
}
printf("tx closed. \n");
}