You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
netpong/check_input.cpp

84 lines
2.6 KiB
C++

#include <iostream>
#include "includes/easysock.h"
#include "includes/connect_code.hpp"
#include "includes/server.hpp"
#include "includes/client.hpp"
#include "includes/check_input.hpp"
#include "includes/raygui/raygui.h"
#include "includes/exception_consts.hpp"
#include "includes/raygui_helpers.hpp"
#include "includes/timer.h"
GameType check_server(char* ip_text, char* port_text) {
GameType type;
std::string addr;
uint16_t port;
/* Check if IP address and port are in valid forms */
if (check_ip_ver(ip_text) < 0) {
throw std::invalid_argument("Invalid IP address");
}
if (port_to_num(port_text) < 0) {
throw std::invalid_argument("Invalid port");
}
/* From here on, we assume that the IP and port are valid */
addr = std::string(ip_text);
port = std::stoi(std::string(port_text));
std::string code = connect_code::encode(addr, std::to_string(port));
/* Create server socket and wait for client to connect */
Server* server = new Server(ES_UDP, addr.data(), port);
server->create_socket();
display_text_centered("Your code is " + code + "\nWaiting for connection...");
std::string response = "";
char* temp_response = NULL;
/* Wait for the client to connect. Since recvAll returns a char*, we need to create a temporary variable to check for NULL.
TODO - Check that the client actually sends 'GG'. */
do {
temp_response = server->recvAll();
} while (temp_response == NULL);
response = std::string(temp_response);
server->sendAll("U2");
display_text_centered("Connection received from " + server->get_peer_addr());
Timer timer = timer_init(3);
while (!timer_done(timer)); // Wait for five seconds
type.mode = M_SERVER;
type.netsock = server;
return type;
}
GameType check_client(char* code_text) {
GameType type;
std::vector<std::string> addr_port;
std::string connect_code = std::string(code_text); /* The connect code is a special string, that contains the server address and port. It is given by the server. */
try {
addr_port = connect_code::decode(connect_code);
Client* client = new Client(ES_UDP, addr_port[0].data(), std::stoi(addr_port[1]));
client->create_socket();
/* Send a specific message to the server, and wait for the appropriate response, to know that the server is ready */
client->sendAll("GG");
// display_text_centered("Connecting...");
std::string msg_from_server = client->recvAll();
if (msg_from_server == "U2") {
display_text_centered("Connection made");
Timer timer = timer_init(3);
while (!timer_done(timer));
} else {
throw EXCEPT_WRONGRESPONSE;
}
type.mode = M_CLIENT;
type.netsock = client;
return type;
} catch (int e) {
throw;
} catch (std::exception& e) {
throw;
}
}