#include #include #include #include #include #include #include #include using std::cerr; using std::cout; using std::endl; using std::ofstream; using std::stoi; using std::string; using std::thread; #define DEBUG class myClient { string name; unsigned short port; unsigned short time; sockaddr_in serverAddress; int clientSocket; public: myClient(string name, unsigned short port, unsigned short time) { this->name = name; this->port = port; this->time = time; this->clientSocket = socket(AF_INET, SOCK_STREAM, 0); this->serverAddress.sin_family = AF_INET; this->serverAddress.sin_port = htons(port); this->serverAddress.sin_addr.s_addr = INADDR_ANY; if (connect(this->clientSocket, (sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) { cerr << "Cannot connect to server!" << endl; exit(-2); } thread t(&myClient::sendData, this); t.join(); } void sendData() { while (1) { std::this_thread::sleep_for(std::chrono::seconds(this->time)); send(this->clientSocket, this->name.c_str(), strlen(this->name.c_str()), 0); } } ~myClient() { close(this->clientSocket); } }; int main(int argc, char *argv[]) { if (argc < 4) { cerr << "Usage: " << argv[0] << " [name] [port] [time(s)]." << endl; exit(-1); } const string name = argv[1]; const unsigned short port = stoi(argv[2]); const unsigned short time = stoi(argv[3]); #ifdef DEBUG cout << "[DEBUG] Starting a client with parameters: " << endl << "Name: " << name << endl << "Port: " << port << endl << "Time: " << time << endl; #endif myClient c(name, port, time); while(1); }