/////////////////////////////////////////////////////// Send a message to the server, wait for the answer ///////////////////////////////////////////////////////
| 49 | /// |
| 50 | //////////////////////////////////////////////////////////// |
| 51 | void runUdpClient(unsigned short port) |
| 52 | { |
| 53 | // Ask for the server address |
| 54 | std::optional<sf::IpAddress> server; |
| 55 | do |
| 56 | { |
| 57 | std::cout << "Type the address or name of the server to connect to: "; |
| 58 | std::string hostname; |
| 59 | std::cin >> hostname; |
| 60 | if (const auto addresses = sf::Dns::resolve(hostname); addresses.has_value() && !addresses->empty()) |
| 61 | server = addresses->front(); |
| 62 | } while (!server.has_value()); |
| 63 | |
| 64 | // Create a socket for communicating with the server |
| 65 | sf::UdpSocket socket; |
| 66 | |
| 67 | // Send a message to the server |
| 68 | static constexpr std::string_view out = "Hi, I'm a client"; |
| 69 | if (socket.send(out.data(), out.size(), server.value(), port) != sf::Socket::Status::Done) |
| 70 | return; |
| 71 | std::cout << "Message sent to the server: " << std::quoted(out.data()) << std::endl; |
| 72 | |
| 73 | // Receive an answer from anyone (but most likely from the server) |
| 74 | std::array<char, 128> in{}; |
| 75 | std::size_t received = 0; |
| 76 | std::optional<sf::IpAddress> sender; |
| 77 | unsigned short senderPort = 0; |
| 78 | if (socket.receive(in.data(), in.size(), received, sender, senderPort) != sf::Socket::Status::Done) |
| 79 | return; |
| 80 | std::cout << "Message received from " << sender.value() << ": " << std::quoted(in.data()) << std::endl; |
| 81 | } |