MCPcopy Create free account
hub / github.com/SFML/SFML / runUdpServer

Function runUdpServer

examples/sockets/UDP.cpp:20–44  ·  view source on GitHub ↗

/////////////////////////////////////////////////////// Launch a server, wait for a message, send an answer. ///////////////////////////////////////////////////////

Source from the content-addressed store, hash-verified

18///
19////////////////////////////////////////////////////////////
20void 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////////////////////////////////////////////////////////////

Callers 1

mainFunction · 0.85

Calls 3

bindMethod · 0.45
receiveMethod · 0.45
sendMethod · 0.45

Tested by

no test coverage detected