client_tcp_select.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #include <sys/select.h>
  10. #define BUFFER_SIZE 256
  11. void error(const char *msg) {
  12. perror(msg);
  13. exit(1);
  14. }
  15. int main()
  16. {
  17. int client_fd;
  18. struct sockaddr_in server;
  19. fd_set readfds;
  20. char buffer[BUFFER_SIZE];
  21. // Create a TCP socket
  22. client_fd = socket(AF_INET, SOCK_STREAM, 0);
  23. if (client_fd < 0)
  24. {
  25. error("Error opening socket.");
  26. }
  27. server.sin_family = AF_INET;
  28. server.sin_addr.s_addr = inet_addr("127.0.0.1"); // Change this to server's IP address
  29. server.sin_port = htons(5000);
  30. // Connect to the server
  31. if (connect(client_fd, (struct sockaddr *)&server, sizeof(server)) < 0)
  32. {
  33. error("Connection error");
  34. }
  35. printf("Connected to the server.\n");
  36. while (1)
  37. {
  38. // Clear the socket set and add client socket to it
  39. FD_ZERO(&readfds);
  40. FD_SET(client_fd, &readfds);
  41. FD_SET(STDIN_FILENO, &readfds); // Add standard input to readfds
  42. // Wait for an activity on one of the sockets
  43. int activity = select(client_fd + 1, &readfds, NULL, NULL, NULL);
  44. if (activity < 0)
  45. {
  46. error("Select error");
  47. }
  48. //If data is received from the server
  49. if (FD_ISSET(client_fd, &readfds))
  50. {
  51. int valread = read(client_fd, buffer, sizeof(buffer));
  52. if (valread > 0)
  53. {
  54. buffer[valread] = '\0'; // Null-terminate the received string
  55. printf("Broadcast from server: %s\n", buffer);
  56. }
  57. }
  58. // If input is available from the console
  59. if (FD_ISSET(STDIN_FILENO, &readfds))
  60. {
  61. fgets(buffer, BUFFER_SIZE, stdin);
  62. buffer[strcspn(buffer, "\n")] = 0; // Remove trailing newline character
  63. send(client_fd, buffer, strlen(buffer), 0);
  64. }
  65. }
  66. close(client_fd);
  67. return 0;
  68. }