Hello!
I try to create a...kind of chat using a UDP socket.
I started with the examples in the tutorial about UDP sockets and I modified them a bit.
I want to create two separate programs (the server and the client) and to communicate each other. Until now, only the client can send messages to the server.
Here is the code for the server application:
#include<SFML/Network.hpp>
#include<iostream>
#include<cstring>
void DoServerUDP(unsigned short Port)
{
// Create a UDP socket for communicating with clients
sf::SocketUDP Server;
// Bind it to the specified port
if (!Server.Bind(Port))
return;
// Receive a message from anyone
sf::IPAddress ClientAddress = sf::IPAddress::LocalHost;
unsigned short ClientPort;
char Message[128];
char SendingMessage[200];
std::size_t Received;
int i=0;
while(i<100)
{
Server.Receive(Message, sizeof(Message), Received, ClientAddress, ClientPort);
std::cout <<"Client: "<< Message << "\n" << std::endl;
/* std::cin.getline(SendingMessage, 200);
Server.Send(SendingMessage,sizeof(SendingMessage), ClientAddress, ClientPort);*/
i++;
}
// Close the socket when we're done
Server.Close();
}
int main()
{
const int port = 2343;
std::cout<<"Hello! The UDP server has been started. Now, the server waits for messages.";
std::cout<<"\n";
DoServerUDP(port);
std::cout<<"Press enter to exit...";
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
And this is the code for the client application:
#include<SFML/Network.hpp>
#include<iostream>
#include<cstring>
void DoClientUDP(unsigned short Port)
{
// Ask for server address
sf::IPAddress ServerAddress;
do
{
std::cout << "Type address or name of the server to send the message to : ";
std::cin >> ServerAddress;
}
while (!ServerAddress.IsValid());
char Message[3000];
// Create a UDP socket for communicating with server
sf::SocketUDP Client;
std::cout<<"You will now start the conversation with server: ";
std::cin.getline(Message, 3000);
std::size_t Received;
char MessageReceived[256];
int i=0;
while(i<100)
{
Client.Send(Message, sizeof(Message), ServerAddress, Port);
std::cin.getline(Message, 3000);
i++;
}
// Close the socket when we're done
Client.Close();
}
int main()
{
const int port = 2343;
std::cout<<"Welcome to the Client application!";
std::cout<<"\n";
DoClientUDP(port);
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return EXIT_SUCCESS;
}
As a server address, I use my local host: 127.0.0.1
How can I modify them so that the server can send messages to the client?
Thank you respectfuly.
P.S. Please excuse my english, I'm not a native speaker.