Hi, I'm working on a game working in multiplayer mode, but I'm facing some problems trying to set up a working server which can accepts more than one connection.
How the server should work to my mindThe server starts, the he wait for new client connection, So I have a loop that is active until the server stop.
For each new connection I start a new thread which willl handle comunication with the client, each client are stored in a map width an id and an object representing the connection. So in the thread method I have a loop which runs while the connection is still alive, in this method I handle pakets.
I have to use packets to tranfers data because the project it is more easier. I use TCP packet.
So I would like to know how this kind of server should be done ? How handle connection/disconnection, receiving packets ...
My problemMy server receive the packet but use almost 20% of the processor, I receive 0 in the packet but it shouldn't because I send 42.
This is what I've done (which doesn't work):Clientbool Client::connect() {
bool success = m_socket.connect(m_host, m_port) == sf::Socket::Done;
if(success){
std::cout << "Connected !" << std::endl;
m_active = true;
std::thread thread(sendData, this);
thread.detach();
}else{
std::cerr << "Unable to connect to server" << std::endl;
}
return success;
}
//Method which send data
void Client::sendData() {
sf::Packet packet;
int i = 42;
packet << i;
m_socket.send(packet);
}
Servervoid Server::start() {
if(m_port == 0){
std::cerr << "Error the server must have a port !" << std::endl;
return;
}
if(m_listener.listen(m_port) != sf::Socket::Done){
std::cerr << "Error while starting server, port is already in use" << std::endl;
return;
}
m_active = true;
std::cout << "Server started on port " << m_port << " waiting for new client..." << std::endl;
sf::TcpSocket clientSocket;
while(m_active){
if(m_listener.accept(clientSocket) != sf::Socket::Done){
std::cerr << "Error while receiving new connection" << std::endl;
}
unsigned short id = generateClientId();
ClientConnection *clientConnection = new ClientConnection(0, clientSocket);
clientConnection->setActive(true);
addClient(id, clientConnection);
clientConnection->listenPackets();
std::cout << "New client connected, starting thread !" << std::endl;
std::thread thread(&ClientConnection::listenPackets, clientConnection);
thread.detach();
}
std::cout << "Server stopped" << std::endl;
}
//Method which receive packets
void ClientConnection::listenPackets() {
sf::Packet packet;
int a;
while(m_active){
m_socket->receive(packet);
while(!packet.endOfPacket()){
packet >> a;
std::cout << "Recu " << a << std::endl;
}
}
}
So here are most interesting parts, any help is welcomed.
Thanks
Clyx.