Back to index

libsfml  1.6+dfsg2
UDP.cpp
Go to the documentation of this file.
00001 
00003 // Headers
00005 #include <SFML/Network.hpp>
00006 #include <iostream>
00007 
00008 
00013 void DoClientUDP(unsigned short Port)
00014 {
00015     // Ask for server address
00016     sf::IPAddress ServerAddress;
00017     do
00018     {
00019         std::cout << "Type address or name of the server to send the message to : ";
00020         std::cin  >> ServerAddress;
00021     }
00022     while (!ServerAddress.IsValid());
00023 
00024     // Create a UDP socket for communicating with server
00025     sf::SocketUDP Client;
00026 
00027     // Send a message to the server
00028     char Message[] = "Hi, I'm a client !";
00029     if (Client.Send(Message, sizeof(Message), ServerAddress, Port) != sf::Socket::Done)
00030         return;
00031     std::cout << "Message sent to server : \"" << Message << "\"" << std::endl;
00032 
00033     // Close the socket when we're done
00034     Client.Close();
00035 }
00036 
00037 
00042 void DoServerUDP(unsigned short Port)
00043 {
00044     // Create a UDP socket for communicating with clients
00045     sf::SocketUDP Server;
00046 
00047     // Bind it to the specified port
00048     if (!Server.Bind(Port))
00049         return;
00050 
00051     // Receive a message from anyone
00052     sf::IPAddress ClientAddress;
00053     unsigned short ClientPort;
00054     char Message[128];
00055     std::size_t Received;
00056     if (Server.Receive(Message, sizeof(Message), Received, ClientAddress, ClientPort) != sf::Socket::Done)
00057         return;
00058 
00059     // Display it
00060     std::cout << "Message received from " << ClientAddress << " on port " << ClientPort
00061               << ": \"" << Message << "\"" << std::endl;
00062 
00063     // Close the socket when we're done
00064     Server.Close();
00065 }