/////////////////////////////////////////////////////// Launch a server, wait for a message, send an answer. ///////////////////////////////////////////////////////
| 18 | /// |
| 19 | //////////////////////////////////////////////////////////// |
| 20 | void runUdpServer(unsigned short port) |
| 21 | { |
| 22 | // Create a socket to receive a message from anyone |
| 23 | sf::UdpSocket socket; |
| 24 | |
| 25 | // Listen to messages on the specified port |
| 26 | if (socket.bind(port) != sf::Socket::Status::Done) |
| 27 | return; |
| 28 | std::cout << "Server is listening to port " << port << ", waiting for a message... " << std::endl; |
| 29 | |
| 30 | // Wait for a message |
| 31 | std::array<char, 128> in{}; |
| 32 | std::size_t received = 0; |
| 33 | std::optional<sf::IpAddress> sender; |
| 34 | unsigned short senderPort = 0; |
| 35 | if (socket.receive(in.data(), in.size(), received, sender, senderPort) != sf::Socket::Status::Done) |
| 36 | return; |
| 37 | std::cout << "Message received from client " << sender.value() << ": " << std::quoted(in.data()) << std::endl; |
| 38 | |
| 39 | // Send an answer to the client |
| 40 | static constexpr std::string_view out = "Hi, I'm the server"; |
| 41 | if (socket.send(out.data(), out.size(), sender.value(), senderPort) != sf::Socket::Status::Done) |
| 42 | return; |
| 43 | std::cout << "Message sent to the client: " << std::quoted(out.data()) << std::endl; |
| 44 | } |
| 45 | |
| 46 | |
| 47 | //////////////////////////////////////////////////////////// |