#include #include #include #include #include #pragma comment(lib, "Ws2_32.lib") #define PORT 8080 #define BUFFER_SIZE 1024 void run_client() { WSADATA wsaData; SOCKET sock; struct sockaddr_in serv_addr; char buffer[BUFFER_SIZE] = {0}; // Initialize Winsock if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("WSAStartup failed\n"); return; } // Create socket if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { printf("Socket creation failed\n"); WSACleanup(); return; } // Set server details serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { printf("Invalid address/ Address not supported\n"); closesocket(sock); WSACleanup(); return; } // Connect to the server if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == SOCKET_ERROR) { printf("Connection Failed\n"); closesocket(sock); WSACleanup(); return; } // Receive welcome message int bytes_received = recv(sock, buffer, BUFFER_SIZE - 1, 0); if (bytes_received > 0) { buffer[bytes_received] = '\0'; // Null-terminate the response printf("%s", buffer); } else { printf("Error receiving initial message\n"); closesocket(sock); WSACleanup(); return; } while (1) { printf("Choose an action:\n1. List Products\n2. Add Product to Cart\n3. Remove Product from Cart\n4. View Cart\n5. Clear Cart\n6. Exit\n"); int choice; scanf("%d", &choice); getchar(); // Consume the newline character memset(buffer, 0, BUFFER_SIZE); // Clear the buffer if (choice == 1) { snprintf(buffer, BUFFER_SIZE, "LIST_PRODUCTS"); } else if (choice == 2) { printf("Enter the product name to add: "); char product_name[BUFFER_SIZE]; fgets(product_name, BUFFER_SIZE, stdin); product_name[strcspn(product_name, "\n")] = 0; // Remove newline snprintf(buffer, BUFFER_SIZE, "ADD %s", product_name); } else if (choice == 3) { printf("Enter the product name to remove: "); char product_name[BUFFER_SIZE]; fgets(product_name, BUFFER_SIZE, stdin); product_name[strcspn(product_name, "\n")] = 0; // Remove newline snprintf(buffer, BUFFER_SIZE, "REMOVE %s", product_name); } else if (choice == 4) { snprintf(buffer, BUFFER_SIZE, "LIST_CART"); } else if (choice == 5) { snprintf(buffer, BUFFER_SIZE, "CLEAR_CART"); } else if (choice == 6) { snprintf(buffer, BUFFER_SIZE, "EXIT"); } // Send user input to the server send(sock, buffer, strlen(buffer), 0); // Receive server response bytes_received = recv(sock, buffer, BUFFER_SIZE - 1, 0); if (bytes_received > 0) { buffer[bytes_received] = '\0'; // Null-terminate the response printf("%s", buffer); } else { printf("Error receiving server response\n"); } // Exit if user chooses to exit if (choice == 6) { break; } } closesocket(sock); WSACleanup(); } int main() { run_client(); return 0; }