/////////////////////////////////////////////////////// Create a client, connect it to a server, display the welcome message and send an answer. ///////////////////////////////////////////////////////
| 107 | /// |
| 108 | //////////////////////////////////////////////////////////// |
| 109 | void runTcpClient(unsigned short port, bool tls) |
| 110 | { |
| 111 | // Ask for the server address |
| 112 | std::optional<sf::IpAddress> server; |
| 113 | do |
| 114 | { |
| 115 | std::cout << "Type the address or name of the server to connect to: "; |
| 116 | std::string hostname; |
| 117 | std::cin >> hostname; |
| 118 | if (const auto addresses = sf::Dns::resolve(hostname); addresses.has_value() && !addresses->empty()) |
| 119 | server = addresses->front(); |
| 120 | } while (!server.has_value()); |
| 121 | |
| 122 | // Create a socket for communicating with the server |
| 123 | sf::TcpSocket socket; |
| 124 | |
| 125 | // Connect to the server |
| 126 | if (socket.connect(server.value(), port) != sf::Socket::Status::Done) |
| 127 | return; |
| 128 | std::cout << "Connected to server " << server.value() << std::endl; |
| 129 | |
| 130 | if (tls) |
| 131 | { |
| 132 | // Setup TLS |
| 133 | if (socket.setupTlsClient(commonName, certificate) != sf::TcpSocket::TlsStatus::HandshakeComplete) |
| 134 | return; |
| 135 | std::cout << "TLS set up" << std::endl; |
| 136 | |
| 137 | if (auto ciphersuite = socket.getCurrentCiphersuiteName(); ciphersuite) |
| 138 | std::cout << "Ciphersuite in use: " << *ciphersuite << std::endl; |
| 139 | } |
| 140 | |
| 141 | // Receive a message from the server |
| 142 | std::array<char, 128> in{}; |
| 143 | std::size_t received = 0; |
| 144 | if (socket.receive(in.data(), in.size(), received) != sf::Socket::Status::Done) |
| 145 | return; |
| 146 | std::cout << "Message received from the server: " << std::quoted(in.data()) << std::endl; |
| 147 | |
| 148 | // Send an answer to the server |
| 149 | static constexpr std::string_view out = "Hi, I'm a client"; |
| 150 | if (socket.send(out.data(), out.size()) != sf::Socket::Status::Done) |
| 151 | return; |
| 152 | std::cout << "Message sent to the server: " << std::quoted(out.data()) << std::endl; |
| 153 | } |
no test coverage detected