|
| 1 | +#include <iostream> |
| 2 | +#include <iomanip> |
| 3 | +#include <cstdlib> |
| 4 | +#include <unistd.h> |
| 5 | +#include <stdio.h> |
| 6 | +#include <sys/socket.h> |
| 7 | +#include <stdlib.h> |
| 8 | +#include <netinet/in.h> |
| 9 | +#include <string.h> |
| 10 | +#include <arpa/inet.h> |
| 11 | +#include <vector> |
| 12 | +#include <cstdlib> |
| 13 | +#include <ctime> |
| 14 | + |
| 15 | +#define PORT 8080 |
| 16 | + |
| 17 | +using namespace std; |
| 18 | + |
| 19 | +// function for string delimiter |
| 20 | +vector<string> split(string s, string delimiter) { |
| 21 | + size_t pos_start = 0, pos_end, delim_len = delimiter.length(); |
| 22 | + string token; |
| 23 | + vector<string> res; |
| 24 | + |
| 25 | + while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { |
| 26 | + token = s.substr (pos_start, pos_end - pos_start); |
| 27 | + pos_start = pos_end + delim_len; |
| 28 | + res.push_back (token); |
| 29 | + } |
| 30 | + |
| 31 | + res.push_back (s.substr (pos_start)); |
| 32 | + return res; |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +int main(int argc, char *argv[]) |
| 37 | +{ |
| 38 | + // /* deal with input arguments*/ |
| 39 | + // std::cout << "print arguments:\nargc == " << argc << '\n'; |
| 40 | + // for(int ndx{}; ndx != argc; ++ndx) { |
| 41 | + // std::cout << "argv[" << ndx << "] == " << argv[ndx] << '\n'; |
| 42 | + // } |
| 43 | + // std::cout << "argv[" << argc << "] == " |
| 44 | + // << static_cast<void*>(argv[argc]) << '\n'; |
| 45 | + |
| 46 | + srand((unsigned int)time(NULL)); // avoid always same output of rand() |
| 47 | + float server_local_clock = rand() % 10; // range from 0 to 9 |
| 48 | + vector<float> clients_local_clocks; |
| 49 | + printf("Sever starts. Server pid is %d \n", getpid()); |
| 50 | + printf("Server local clock is %f \n\n", server_local_clock); |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | + // Socket Cite: https://www.geeksforgeeks.org/socket-programming-cc/?ref=lbp |
| 55 | + int server_socket_fd, new_socket, valread; |
| 56 | + vector<int> client_sockets; |
| 57 | + vector<string> client_ips; |
| 58 | + vector<int> client_ports; |
| 59 | + struct sockaddr_in server_address; |
| 60 | + server_address.sin_family = AF_INET; // IPv4 |
| 61 | + server_address.sin_addr.s_addr = INADDR_ANY; // localhost |
| 62 | + server_address.sin_port = htons( PORT ); // 8080 |
| 63 | + int opt = 1; // for setsockopt |
| 64 | + |
| 65 | + // Creating socket file descriptor (IPv4, TCP, IP) |
| 66 | + if ((server_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) |
| 67 | + { |
| 68 | + perror("Server: socket failed"); |
| 69 | + exit(EXIT_FAILURE); |
| 70 | + } |
| 71 | + |
| 72 | + // Optional: it helps in reuse of address and port. Prevents error such as: “address already in use”. |
| 73 | + if (setsockopt(server_socket_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, |
| 74 | + &opt, sizeof(opt))) |
| 75 | + { |
| 76 | + perror("Server: setsockopt"); |
| 77 | + exit(EXIT_FAILURE); |
| 78 | + } |
| 79 | + |
| 80 | + // Forcefully attaching socket to the port 8080 |
| 81 | + if (bind(server_socket_fd, (struct sockaddr *)&server_address, |
| 82 | + sizeof(server_address))<0) |
| 83 | + { |
| 84 | + perror("Server: bind failed"); |
| 85 | + exit(EXIT_FAILURE); |
| 86 | + } |
| 87 | + |
| 88 | + // Putting the server socket in a passive mode, waiting for the client to approach the server to make a connection |
| 89 | + // The backlog=7, defines the maximum length to which the queue of pending connections for sockfd may grow. |
| 90 | + // If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED. |
| 91 | + if (listen(server_socket_fd, 7) < 0) |
| 92 | + { |
| 93 | + perror("Server: listen"); |
| 94 | + exit(EXIT_FAILURE); |
| 95 | + } |
| 96 | + printf("Server: server is listening ...\n\nYou can open one or multiple new terminal windows now to run ./client\n"); |
| 97 | + int clients_ctr = 0; |
| 98 | + |
| 99 | + |
| 100 | + // Setting up buffer for receiving msg |
| 101 | + char recv_buf[65536]; |
| 102 | + memset(recv_buf, '\0', sizeof(recv_buf)); |
| 103 | + |
| 104 | + int in_client_enough = 0; |
| 105 | + while ( in_client_enough == 0) { // block on accept() until positive fd or error |
| 106 | + struct sockaddr_in client_addr; |
| 107 | + socklen_t length = sizeof(client_addr); |
| 108 | + // Extracting the first connection request on the queue of pending connections for the listening socket (server_socket_fd) |
| 109 | + // Creates a new connected socket, and returns a new file descriptor referring to that socket |
| 110 | + if ((new_socket = accept(server_socket_fd, (struct sockaddr *)&client_addr, |
| 111 | + (socklen_t*)&length))<0) |
| 112 | + { |
| 113 | + perror("Server: accept"); |
| 114 | + exit(EXIT_FAILURE); |
| 115 | + } |
| 116 | + |
| 117 | + clients_ctr ++; |
| 118 | + printf("\nYou have connected %d client(s) now.", clients_ctr); |
| 119 | + |
| 120 | + // converting the network address structure src in the af address family into a character string. |
| 121 | + char client_ip[INET_ADDRSTRLEN] = ""; |
| 122 | + inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN); |
| 123 | + printf("Server: new client accepted. client ip and port: %s:%d\n", client_ip, ntohs(client_addr.sin_port)); |
| 124 | + |
| 125 | + |
| 126 | + // store new client connection into array |
| 127 | + client_sockets.push_back(new_socket); |
| 128 | + client_ips.push_back(client_ip); |
| 129 | + client_ports.push_back(ntohs(client_addr.sin_port)); |
| 130 | + |
| 131 | + printf("current connected clients amount is %d \n", int(client_sockets.size()) ); |
| 132 | + |
| 133 | + cout << "Do you have enought clients? (please input '1' for yes, '0' for no):" ; |
| 134 | + cin >> in_client_enough; |
| 135 | + if (in_client_enough == 0){ |
| 136 | + cout << "OK. Please continute opening one or multiple new terminal windows to run ./client\n" << endl; |
| 137 | + }else if (in_client_enough != 1){ |
| 138 | + cout << "Unrecognized input has been considered as 0. You can create one more client.\n" << endl; |
| 139 | + in_client_enough = 0; |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + |
| 144 | + printf("\nClients creation finished! There are totally %d connected clients.\n", int(client_sockets.size()) ); |
| 145 | + printf("Asking all clients to report their local clock value ... \n\n\n"); |
| 146 | + |
| 147 | + |
| 148 | + for (int i = 0; i < client_sockets.size(); i++){ |
| 149 | + // sending a message to client |
| 150 | + const char *msg = "Hello from server, please tell me your local clock value."; |
| 151 | + send(client_sockets[i] , msg , strlen(msg) , 0 ); |
| 152 | + printf("Server: sent to client(%s:%d): '%s'\n", client_ips[i].c_str(), client_ports[i], msg); |
| 153 | + |
| 154 | + |
| 155 | + // receiving |
| 156 | + while(recv(client_sockets[i], recv_buf, sizeof(recv_buf), 0) > 0 ){ |
| 157 | + printf("Server: recv from client(%s:%d): '%s' \n", client_ips[i].c_str(), client_ports[i], recv_buf); |
| 158 | + |
| 159 | + // convert char array to string |
| 160 | + string recv_msg = string(recv_buf); |
| 161 | + |
| 162 | + if (recv_msg.find("Hello from client, my local clock value is") != string::npos){ |
| 163 | + string substr_after_last_space; |
| 164 | + vector<string> split_str = split(recv_msg, " "); |
| 165 | + substr_after_last_space = split_str[ split_str.size() - 1 ]; |
| 166 | + |
| 167 | + cout << "Server: received client local clock (string) is " << substr_after_last_space << endl; |
| 168 | + float substr_after_last_space_f = stof(substr_after_last_space); |
| 169 | + cout << "Server: received client local clock (float) is " << substr_after_last_space_f << endl; |
| 170 | + |
| 171 | + clients_local_clocks.push_back(substr_after_last_space_f); |
| 172 | + } |
| 173 | + |
| 174 | + memset(recv_buf, '\0', strlen(recv_buf)); |
| 175 | + break; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + printf("\n\n"); |
| 180 | + |
| 181 | + // average clock values |
| 182 | + float all_clock_sum = server_local_clock; |
| 183 | + for (int i = 0; i < clients_local_clocks.size(); i++){ |
| 184 | + all_clock_sum += clients_local_clocks[i]; |
| 185 | + } |
| 186 | + float avg_clock = all_clock_sum / (client_sockets.size() + 1); |
| 187 | + |
| 188 | + // tell clients how to adjust |
| 189 | + for (int i = 0; i < client_sockets.size(); i++){ |
| 190 | + // prepare msg |
| 191 | + float offset = clients_local_clocks[i] - avg_clock; |
| 192 | + string operation; |
| 193 | + if (offset >= 0){ |
| 194 | + operation = "minus"; |
| 195 | + }else{ |
| 196 | + operation = "add"; |
| 197 | + offset = 0 - offset; |
| 198 | + } |
| 199 | + string msg_str = "From server, your clock adjustment offset is " + operation + " " + to_string(offset); |
| 200 | + char msg_char_array[msg_str.length() + 1]; |
| 201 | + strcpy(msg_char_array, msg_str.c_str()); |
| 202 | + // sending a message to client |
| 203 | + send(client_sockets[i] , &msg_char_array , strlen(msg_char_array) , 0 ); |
| 204 | + printf("Server: sent to client(%s:%d): '%s'\n", client_ips[i].c_str(), client_ports[i], msg_char_array); |
| 205 | + |
| 206 | + } |
| 207 | + |
| 208 | + // adjust self |
| 209 | + server_local_clock += avg_clock - server_local_clock; |
| 210 | + printf("\n\nServer new local clock is %f \n\n", server_local_clock); |
| 211 | + |
| 212 | + |
| 213 | + printf("Server: server stopped. \n"); |
| 214 | + close(server_socket_fd); |
| 215 | + return 0; |
| 216 | +} |
0 commit comments