I've begun work on adding multiplayer to my RTS game, but I've gotten a bit stuck.
So with a simple chat application, the server will wait until a client sends something, then they can send that to all the other clients. My question is how do other clients recieve data if they are busy sending it?
In the code below, the server recieves the message, but how would I go about sending the messages to all the clients once it arrives?
Thanks.
Here's my attempt from code from the tutorials.
(I know there are memory leaks.)
#include <SFML/System.hpp>
#include <SFML/Network.hpp>
#include <vector>
#include <iostream>
#include <ctime>
#include <cstring>
int PORT = 1234;
class GameServer
{
public:
GameServer() {};
~GameServer() {};
void RecieveConnections()
{
sf::SocketTCP Listener;
if (!Listener.Listen(PORT))
return;
std::cout << "Listening to port " << PORT << ", waiting for connections..." << std::endl;
sf::SelectorTCP Selector;
Selector.Add(Listener);
while (true)
{
std::cout << "Waiting..." << std::endl;
unsigned int NbSockets = Selector.Wait();
for (unsigned int i = 0; i < NbSockets; ++i)
{
sf::SocketTCP Socket = Selector.GetSocketReady(i);
if (Socket == Listener)
{
sf::IPAddress Address;
sf::SocketTCP Client;
Listener.Accept(Client, &Address);
std::cout << "Client connected ! (" << Address << ")" << std::endl;
Selector.Add(Client);
_client_sockets.push_back(&Client);
}
else
{
sf::Packet Packet;
if (Socket.Receive(Packet) == sf::Socket::Done)
{
std::string Message;
Packet >> Message;
std::cout << "A client says : \"" << Message << "\"" << std::endl;
}
else
{
Selector.Remove(Socket);
}
}
}
}
}
private:
std::vector<sf::SocketTCP*> _client_sockets;
};
class VirtualGame
{
public:
VirtualGame()
{
};
~VirtualGame() {};
void Run()
{
std::cerr << "Attempting to connect" << std::endl;
if (_socket.Connect(PORT,"127.0.0.1") != sf::Socket::Done)
{
std::cerr << "Unable to connect" << std::endl;
}
else
{
std::cerr << "connected" << std::endl;
bool Connected = true;
while (true)
{
std::string Message;
std::cout << "Say something to the server : ";
std::getline(std::cin, Message);
sf::Packet Packet;
Packet << Message;
_socket.Send(Packet);
}
}
}
private:
sf::SocketTCP _socket;
};
int main()
{
char w;
std::cout << "Enter 's' for server or anything else for client" << std::endl;
std::cin >> w;
if (w=='s')
{
GameServer gameserver = GameServer();
gameserver.RecieveConnections();
}
else
{
VirtualGame *virtualgame = new VirtualGame();
virtualgame->Run();
}
}