#include #include #include #include #include #include #include "tcp_common.h" void *worker(void *arg) { int sockfd = *(int *)arg; for (;;) { char reply[DATA_LEN]; ssize_t length = recv(sockfd, reply, sizeof(reply), 0); if (length <= 0) { puts("Lose connection to server"); shutdown(sockfd, SHUT_RDWR); return 0; } while (reply[strlen(reply) - 1] == '\n') reply[strlen(reply) - 1] = 0; switch (reply[0]) { case TYPE_MSG: { int clino, offset; sscanf(reply + 1, "%d\n%n", &clino, &offset); offset++; printf("--- Message From No.%d ---\n", clino); puts(reply + offset); puts("--- Message End ---"); break; } case TYPE_SUC: puts("--- Server Reply Begin ---"); puts(reply + 1); puts("--- Server Reply End ---"); break; case TYPE_ERR: puts("--- Server Error Begin ---"); puts(reply + 1); puts("--- Server Error End ---"); break; } } } int request(int sockfd, char type, char *msg) { char data[strlen(msg) + 2]; data[0] = type; data[1] = 0; strcat(data, msg); return send(sockfd, data, sizeof(data), 0); } int main(int argc, char *argv[]) { int sockfd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); for (;;) { if (servaddr.sin_family) { printf("You have connected to %s:%hd. Please select one option from the list below:\n", inet_ntoa(servaddr.sin_addr), ntohs(servaddr.sin_port)); puts("1. Disconnect from the server."); puts("2. Retrieve the server time."); puts("3. Retrieve the server name."); puts("4. Retrieve the list of clients."); puts("5. Send a message."); puts("6. Quit."); int number; scanf("%d", &number); switch (number) { case 1: shutdown(sockfd, SHUT_RDWR); sockfd = socket(PF_INET, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr)); break; case 2: request(sockfd, TYPE_TIME, ""); break; case 3: request(sockfd, TYPE_NAME, ""); break; case 4: request(sockfd, TYPE_LIST, ""); break; case 5: { while (getchar() != '\n'); char msg[DATA_LEN]; puts("Enter the number of client to which you want to send the message:"); fgets(msg, DATA_LEN, stdin); puts("Enter the message to send:"); fgets(msg + strlen(msg), DATA_LEN - strlen(msg), stdin); request(sockfd, TYPE_SEND, msg); break; } default: shutdown(sockfd, SHUT_RDWR); return 0; } } else { puts("You have not connected to a server. Please select one option from the list below:"); puts("1. Connect."); puts("2. Quit."); int number; scanf("%d", &number); switch (number) { case 1: puts("Enter the IP address and port number: (e.g. 127.0.0.1:80)"); char ipaddr[IPADDR_LEN]; in_port_t port; scanf("\n%[^:]:%hu", ipaddr, &port); servaddr.sin_family = PF_INET; inet_aton(ipaddr, &servaddr.sin_addr); servaddr.sin_port = htons(port); int ret = connect(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)); if (ret == 0) { pthread_t tid; pthread_create(&tid, NULL, worker, &sockfd); } else { memset(&servaddr, 0, sizeof(servaddr)); puts("Connection failed"); } break; default: return 0; } } } }