1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <sys/select.h>
- #define BUFFER_SIZE 256
- void error(const char *msg) {
- perror(msg);
- exit(1);
- }
- int main()
- {
- int client_fd;
- struct sockaddr_in server;
- fd_set readfds;
- char buffer[BUFFER_SIZE];
- // Create a TCP socket
- client_fd = socket(AF_INET, SOCK_STREAM, 0);
- if (client_fd < 0)
- {
- error("Error opening socket.");
- }
- server.sin_family = AF_INET;
- server.sin_addr.s_addr = inet_addr("127.0.0.1"); // Change this to server's IP address
- server.sin_port = htons(5000);
- // Connect to the server
- if (connect(client_fd, (struct sockaddr *)&server, sizeof(server)) < 0)
- {
- error("Connection error");
- }
- printf("Connected to the server.\n");
- while (1)
- {
- // Clear the socket set and add client socket to it
- FD_ZERO(&readfds);
- FD_SET(client_fd, &readfds);
- FD_SET(STDIN_FILENO, &readfds); // Add standard input to readfds
- // Wait for an activity on one of the sockets
- int activity = select(client_fd + 1, &readfds, NULL, NULL, NULL);
- if (activity < 0)
- {
- error("Select error");
- }
- //If data is received from the server
- if (FD_ISSET(client_fd, &readfds))
- {
- int valread = read(client_fd, buffer, sizeof(buffer));
- if (valread > 0)
- {
- buffer[valread] = '\0'; // Null-terminate the received string
- printf("Broadcast from server: %s\n", buffer);
- }
- }
- // If input is available from the console
- if (FD_ISSET(STDIN_FILENO, &readfds))
- {
- fgets(buffer, BUFFER_SIZE, stdin);
- buffer[strcspn(buffer, "\n")] = 0; // Remove trailing newline character
- send(client_fd, buffer, strlen(buffer), 0);
- }
- }
- close(client_fd);
- return 0;
- }
|