//server.c
int main() {
time(&start);
// Call a function to handle agent login
pid_t child_pid;
// Declare variables for socket creation and binding
int i = 1;
struct sockaddr_in address;
int adlength,valread;
// Create a socket using socket() system call
int sock = create_socket();
if (sock == -1) {
// If there was an error creating the socket, print an error message
printf("\n*************Socket Error!*******************\n");
}
// Bind server’s address and port using bind() system call
connect__data result = bind_port(sock);
// Get the address and address length from the connect_data struct
address = result.adres;
adlength = result.address_length;
// Get the bind result from the connect_data struct
int bind_res = result.bind_result;
// Convert the socket into a listening socket using listen() system call
if (listen(sock, MAX_CLIENTS) < 0) {
// If there was an error setting the socket to listen, print an error message
printf("Listen Error!\n");
return 1;
}
// Accept client connections using accept() system call
printf("\nServer is listening on port %d....\n\n", PORT);
while (1) {
int new_socket = accept(sock, (struct sockaddr*)&address, (socklen_t*)&adlength);
printf("Client-%d connected\n",i);
if (new_socket < 0) {
// If there was an error accepting the client connection, print an error message
printf("Accept Error!\n");
return 1;
}
if ((child_pid == fork()) == 0) {
close(sock);
char buffer_array[1024];
char result_array[1024];
double result_num;
valread = read(new_socket, buffer_array, strlen(buffer_array));
buffer_array[strlen(buffer_array)-1] = '\0';
printf("Received data = '%s' from [ Client-%d ]\n", buffer_array, i);
result_num = compute_postfix_expression(buffer_array);
sprintf(result_array, "%.1f", result_num);
send(new_socket, result_array, strlen(result_array), 0);
FILE* file = fopen("server_records.txt", "a");
if (file != NULL) {
time(¤t);
double time_diff = difftime(current, start);
fprintf(file, "[ Client ID: '%d' ], [ Query: '%s' ]. [Answer: '%s' ], [Time Elapsed(sec): '%.0f'] \n\n", i, buffer_array, result_array, time_diff);
fclose(file);
}
close(new_socket);
exit(0);
}
i++;
close(new_socket);
}
return 0;
}