To use TTP2 in your project you need to include it in first.
After including TTP2 to your project you can start to program the server.
- Create a server tcp socket is set non blocking (SOCK_NONBLOCK):
sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(PORT); serverAddress.sin_addr.s_addr = inet_addr(IP); int serverSocket = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if(bind(serverSocket, (structsockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { std::wcout << "Bind failed!" << std::endl; return -1; }
- TTP2 operates internally using epoll; therefore, client accepts should also be handled with epoll.
- Now you can create an instance of the ServerSessionController
auto serverSessionController = std::make_shared<ServerSessionController>(serverSocket, clientSocket); - Create a networkingSession thread
std::thread networkingSession([serverSessionController]() { serverSessionController->networkingSession(); });
- Take a look at the full implementation here
Done! It is almost the same with the client:
- Create a client tcp socket like such:
int serverSocket = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); sockaddr_in serverAddress; serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(PORT); serverAddress.sin_addr.s_addr = inet_addr(IP); int connectionResult = connect(serverSocket, (structsockaddr*) &serverAddress, sizeof(serverAddress)); if (connectionResult < 0 && errno != EINPROGRESS) { std::wcout << "Connection failed!" << std::endl; return -1; }
- Create an instance of the ClientSessionController
auto clientSessionController = std::make_shared<ClientSessionController>(serverSocket); - Create a networkingSession thread
std::thread networkThread([clientSessionController]() { clientSessionController->networkingSession(); });
- Take a look at the full implementation here
Now you can enjoy TTP2 with the functions provided below:
Common:
void networkingSession();
bool isConnected()
void disconnect()
bool hasRequest()
bool hasResponse()
Packet popRequest()
Packet popResponse()
int getRequestQueueSize()
int getResponseQueueSize()
void pushResponse(Packet)
void pushRequest(Packet request)
int sendMessage(int socket, int id, int method, std::string payload)
int sendPacket(int socket, Packet packet)
Packet receiveMessage(int socket)
Packet
structPacket { int id; int method; std::string payload; };
ClientSessionController specific:
- ClientSessionController();
- ClientSessionController(int &socket);
ServerSessionController specific:
- ServerSessionController();
- ServerSessionController(int serverSocket, int clientSocket);
- std::string getLocalIpAddress(std::string interface);
To test the TTP2 protocol you need to start the server first using:
nix run .#server
After that you can start the client with:
nix run .#client