PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/sockets/UDP.cpp

http://github.com/LaurentGomila/SFML
C++ | 72 lines | 42 code | 11 blank | 19 comment | 12 complexity | 417211c7aceca25c3d76dacc79a06e2d MD5 | raw file
  1. ////////////////////////////////////////////////////////////
  2. // Headers
  3. ////////////////////////////////////////////////////////////
  4. #include <SFML/Network.hpp>
  5. #include <iostream>
  6. ////////////////////////////////////////////////////////////
  7. /// Launch a server, wait for a message, send an answer.
  8. ///
  9. ////////////////////////////////////////////////////////////
  10. void runUdpServer(unsigned short port)
  11. {
  12. // Create a socket to receive a message from anyone
  13. sf::UdpSocket socket;
  14. // Listen to messages on the specified port
  15. if (socket.bind(port) != sf::Socket::Done)
  16. return;
  17. std::cout << "Server is listening to port " << port << ", waiting for a message... " << std::endl;
  18. // Wait for a message
  19. char in[128];
  20. std::size_t received;
  21. sf::IpAddress sender;
  22. unsigned short senderPort;
  23. if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
  24. return;
  25. std::cout << "Message received from client " << sender << ": \"" << in << "\"" << std::endl;
  26. // Send an answer to the client
  27. const char out[] = "Hi, I'm the server";
  28. if (socket.send(out, sizeof(out), sender, senderPort) != sf::Socket::Done)
  29. return;
  30. std::cout << "Message sent to the client: \"" << out << "\"" << std::endl;
  31. }
  32. ////////////////////////////////////////////////////////////
  33. /// Send a message to the server, wait for the answer
  34. ///
  35. ////////////////////////////////////////////////////////////
  36. void runUdpClient(unsigned short port)
  37. {
  38. // Ask for the server address
  39. sf::IpAddress server;
  40. do
  41. {
  42. std::cout << "Type the address or name of the server to connect to: ";
  43. std::cin >> server;
  44. }
  45. while (server == sf::IpAddress::None);
  46. // Create a socket for communicating with the server
  47. sf::UdpSocket socket;
  48. // Send a message to the server
  49. const char out[] = "Hi, I'm a client";
  50. if (socket.send(out, sizeof(out), server, port) != sf::Socket::Done)
  51. return;
  52. std::cout << "Message sent to the server: \"" << out << "\"" << std::endl;
  53. // Receive an answer from anyone (but most likely from the server)
  54. char in[128];
  55. std::size_t received;
  56. sf::IpAddress sender;
  57. unsigned short senderPort;
  58. if (socket.receive(in, sizeof(in), received, sender, senderPort) != sf::Socket::Done)
  59. return;
  60. std::cout << "Message received from " << sender << ": \"" << in << "\"" << std::endl;
  61. }