1+ #include < iostream>
2+ #include " Polymorph/Network/udp/Client.hpp"
3+ #include " MessageDto.hpp"
4+
5+
6+ int main (int ac, char **av)
7+ {
8+ using namespace polymorph ::network;
9+ using namespace polymorph ::network::udp;
10+
11+ if (ac != 3 ) {
12+ std::cerr << " Usage: " << av[0 ] << " <host> <port>" << std::endl;
13+ return 1 ;
14+ }
15+
16+ std::map<OpId, bool > safeties = {
17+ { MessageDto::opId, true } // we want the client to resend the message if it doesn't receive an ACK
18+ };
19+ // we create a client and bind its connector
20+ Client client (av[1 ], std::stoi (av[2 ]), safeties);
21+ auto connector = std::make_shared<Connector>(client);
22+ client.setConnector (connector);
23+ connector->start ();
24+
25+ // check variables for the example
26+ std::atomic<bool > received (false );
27+ std::atomic<bool > connected (false );
28+ MessageDto dto { .message = " Hello World!" };
29+
30+ // we register a callback that will handle the received MessageDto
31+ client.registerReceiveHandler <MessageDto>(MessageDto::opId, [&received](const PacketHeader &, const MessageDto &payload) {
32+ received = true ;
33+ std::cout << " Received: " << payload.message << std::endl;
34+ });
35+
36+ // Then we connect to the server and pass a callback that will be called when the connection is established
37+ client.connect ([&connected](bool authorized, SessionId) {
38+ if (authorized) {
39+ std::cout << " Connected" << std::endl;
40+ connected = true ;
41+ } else {
42+ std::cout << " Connection failed" << std::endl;
43+ }
44+ });
45+
46+ // we wait for the connection to be established or the timeout to be reached (5 * 100ms)
47+ int connected_max_tries = 5 ;
48+ while (!connected && --connected_max_tries > 0 ) {
49+ std::this_thread::sleep_for (std::chrono::milliseconds (100 ));
50+ }
51+ assert (connected); // abort if we couldn't connect
52+
53+ // we send the MessageDto to the server
54+ client.send <MessageDto>(MessageDto::opId, dto, [](const PacketHeader &header, const MessageDto &payload) {
55+ std::cout << " Message has been sent" << std::endl;
56+ });
57+
58+ // we wait the registered callback to be called
59+ while (!received)
60+ std::this_thread::sleep_for (std::chrono::milliseconds (100 )); // sleep until we received the echoed message
61+
62+ return 0 ;
63+ }
0 commit comments