/////////////////////////////////////////////////////// Launch a server, wait for an incoming connection, send a message and wait for the answer. ///////////////////////////////////////////////////////
| 57 | /// |
| 58 | //////////////////////////////////////////////////////////// |
| 59 | void runTcpServer(unsigned short port, bool tls) |
| 60 | { |
| 61 | // Create a server socket to accept new connections |
| 62 | sf::TcpListener listener; |
| 63 | |
| 64 | // Listen to the given port for incoming connections |
| 65 | if (listener.listen(port) != sf::Socket::Status::Done) |
| 66 | return; |
| 67 | std::cout << "Server is listening to port " << port << ", waiting for connections... " << std::endl; |
| 68 | |
| 69 | // Wait for a connection |
| 70 | sf::TcpSocket socket; |
| 71 | if (listener.accept(socket) != sf::Socket::Status::Done) |
| 72 | return; |
| 73 | std::cout << "Client connected: " << socket.getRemoteAddress().value() << std::endl; |
| 74 | |
| 75 | if (tls) |
| 76 | { |
| 77 | // Setup TLS |
| 78 | if (socket.setupTlsServer(certificate, privateKey) != sf::TcpSocket::TlsStatus::HandshakeComplete) |
| 79 | { |
| 80 | std::cout << "TLS handshake could not be completed" << std::endl; |
| 81 | return; |
| 82 | } |
| 83 | std::cout << "TLS set up" << std::endl; |
| 84 | |
| 85 | if (auto ciphersuite = socket.getCurrentCiphersuiteName(); ciphersuite) |
| 86 | std::cout << "Ciphersuite in use: " << *ciphersuite << std::endl; |
| 87 | } |
| 88 | |
| 89 | // Send a message to the connected client |
| 90 | static constexpr std::string_view out = "Hi, I'm the server"; |
| 91 | if (socket.send(out.data(), out.size()) != sf::Socket::Status::Done) |
| 92 | return; |
| 93 | std::cout << "Message sent to the client: " << std::quoted(out.data()) << std::endl; |
| 94 | |
| 95 | // Receive a message back from the client |
| 96 | std::array<char, 128> in{}; |
| 97 | std::size_t received = 0; |
| 98 | if (socket.receive(in.data(), in.size(), received) != sf::Socket::Status::Done) |
| 99 | return; |
| 100 | std::cout << "Answer received from the client: " << std::quoted(in.data()) << std::endl; |
| 101 | } |
| 102 | |
| 103 | |
| 104 | //////////////////////////////////////////////////////////// |
no test coverage detected