cocosushi
cocosushi

Reputation: 144

Handling multiple client sockets with SFML

I am currently trying to write the networking part of a little multiplayer game, and I am facing a problem to store my TCP sockets which are, in SFML, non-copyable (I am a beginner in C++).

I have three classes : Server, Client (a server-side class used to store all informations about a connecting client) and ClientManager, which is in charge of storing all clients and giving them IDs, etc.

ClientManager.h

    class ClientManager {
    public:
        ClientManager();
        std::map<int, Net::Client*> getClients();
        int attribID();
        void addClient(Net::Client *client);
        sf::TcpSocket getClientSocket(int id) throw(std::string);
        void setClientSocket(int id, sf::TcpSocket);
    private:
        std::map<int, Net::Client*> m_clients;
        std::map<int, sf::TcpSocket> m_clientSockets;
        std::vector<int> m_ids;
        int m_lastID;
};

What I planned to do originally, when a client connects, is :

void Net::Server::waitForClient() {
   while(true) {
    if(m_listener.accept(m_tcpSocket) != Socket::Done) {
        cout << "Error happened during client connection. skipping. " << endl;
        return;
    }
    int newID = m_clientManager.attribID();
    this->m_clientManager.addClient(new Net::Client(newID, m_tcpSocket, m_tcpSocket.getRemoteAddress()));
   }
}

So, adding a new Client into ClientManager's list, with its ID, a TcpSocket to send info and his address.

But, the problem is that SFML's TcpSocket class is not copyable, which means I can't copy it to a Client like this.

I could pass it as a pointer to the original TcpSocket, but what if another client connects ? The data the pointer points to will have change and the program will bug. I do not know if this behavior will be the same with smart pointers, but I think so (but I don't master them at all).

Storing them in a std::map or std::vector causes the same problem, as they both copy the object. Storing them as pointers (in the map) to the original TcpSocket will cause the same problem as before, because the socket will change too, and the pointers will point to the same object.

How can I store my sockets without having to use references, pointers or to copy my object ?

Any help will be greatly appreciated :)

Upvotes: 1

Views: 1540

Answers (1)

Jonny Paton
Jonny Paton

Reputation: 397

It's going to be a real pain to do without pointers. Personally I use smart pointers to manage the sockets themselves (std::vector<std::unique_ptr<sf::TcpSocket>> or similiar), along with `sf::SocketSelector' to manage the actual communication

Upvotes: 1

Related Questions