/* * client.cpp * * Simulation of Chandy-Lamport algorithm * * This file is a part of Distributed Systems term thesis * Department KIV, ZCU Plzen * Author: Martin Sloup, msloup@students.zcu.cz */ #include #include #include #include #include #include #include #include #include #include #include "client.h" #include "packet.h" #include "util.h" #include "server.h" #include "marker.h" using namespace std; vector clients; pthread_t client_thread; int client_connect(char *hostname, int port) { int c = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (c < 0) { fatal("Creating socket error."); } // prepare hostname_sockaddr using the result from gethostbyname methd sockaddr_in hostname_sockaddr; struct hostent *hostnameInfo; hostnameInfo = gethostbyname(hostname); hostname_sockaddr.sin_family = PF_INET; memcpy(&hostname_sockaddr.sin_addr, hostnameInfo->h_addr, hostnameInfo->h_length); hostname_sockaddr.sin_port = htons(port); printf("Connecting to %s:%d...\n", hostname, port); if (connect(c, (sockaddr*) &hostname_sockaddr, sizeof(sockaddr_in)) < 0) { return -1; } printf("Connected.\n"); return c; } void client_parse_and_connect(const char *filename) { char errmsg[256]; char line[256]; char hostname[256]; long for_branch_id; int port; ifstream file; file.open(filename, ifstream::in); // parse every line in file while(file.good()) { file.getline((char*)&line, 256); // look for channel definition if (sscanf((char*)&line, "%ld %s %d", &for_branch_id, (char*)&hostname, &port) == 0) { if (sscanf((char*)&line, "%s %d", (char*)&hostname, &port) == 0) { continue; } for_branch_id = branch_id; } if (for_branch_id != branch_id) continue; // connect to another branch int c = client_connect(hostname, port); if (c < 0) { sprintf(errmsg, "Can not connect to %s:%d", hostname, port); fatal(errmsg); continue; } clients.push_back(c); } } void *client_thread_run(void *arg) { while(true) { sleep((random() % 4) + 1); if (clients.size() == 0) continue; int c = clients.at(random() % clients.size()); int price = (random() % 50) + 1; // if is enough account balance, transfer money to another branch if (amount - price > 0) { marker_begin(); amount-= price; write_to_mark_log(); marker_end(); packet_send(c, OPER_AMOUNT_TRANSFER, price); } } return NULL; } void client_start() { // start a new client thread for transferring money pthread_create(&client_thread, NULL, client_thread_run, NULL); }