#include "SDL/SDL_net.h"
#include "SDL/SDL_thread.h"
The first is used to create TCP/IP sockets and the second allows our server to create threads. We also use a vector from the Standard Template Library:
#include <vector>
The vector will be used to hold the individual threads that will be created each time a client connects to the server. Here is the vector initialization within main:
std::vector<SDL_Thread*> clients;
And here is the new thread creation after a new client is connected:
client_sockets[FREE_CLIENT_SLOT] = SDLNet_TCP_Accept(server_socket);
if (client_sockets[FREE_CLIENT_SLOT])
{
clients.push_back(SDL_CreateThread(client_thread, &client_sockets[FREE_CLIENT_SLOT]));
}
The idea is to accept a TCPsocket returned by SDLNet_TCP_Accept and then create and push a thread onto the "clients" vector. Function "client_thread" contains all the logic for accepting game related data from the client and it is also provided with a pointer to the client TCPsocket so it can read the data send by the client.
At this point I think the server has to create a new thread which will create a socket to the client in order for the server to feed information to the client. The reason for that is that the SDL_net library only provides blocked reads for reading socket data. I would feel uncomfortable using just a single socket for passing data back and forth from server and client since both server and client could get to a state where they are waiting for the other side to send data (resulting in a deadlock that would not be easily broken). Here is a graphical representation of the design:
By next week I should have a server with which I can test this design and see if it works for a couple of clients connecting to the server. The above design requires the clients to be themselves servers once they connect to the game server.
If you have experience with such a design please do not hesitate to comment. This is just an exercise so I can stay close to programming with C++ since my work does not require me to write in this language anymore.
~Panos
No comments:
Post a Comment