123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <arpa/inet.h>
- #define PORT 8081
- #define BUFFER_SIZE 1024
- // structure to store client data
- typedef struct {
- int client_socket;
- struct sockaddr_in client_addr;
- } client_data_t;
- //function to handle thread
- void *handle_client(void *arg)
- {
- client_data_t *data = (client_data_t *)arg;
- int client_socket = data->client_socket;
- struct sockaddr_in client_addr = data->client_addr;
- char buffer[BUFFER_SIZE]={0};
- int n;
- printf("client connected\n");
- while(1)
- {
- n = recv(client_socket, buffer, sizeof(buffer), 0);
- if (n <= 0)
- {
- printf("Client disconnected\n");
- break;
- }
- printf("Received from client: %s\n", buffer);
- send(client_socket, buffer, strlen(buffer), 0);
- }
- close(client_socket);
- free(data); // Free the memory allocated for client data
- pthread_exit(NULL);
- }
- void main()
- {
- int server_socket, client_socket;
- struct sockaddr_in server_addr={0}, client_addr;
- socklen_t client_len = sizeof(client_addr);
- pthread_t thread_id;
- // create server socket
- if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
- {
- perror("Socket creation failed");
- exit(EXIT_FAILURE);
- }
- // server address setup
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = INADDR_ANY; // Listen on all interfaces
- server_addr.sin_port = htons(PORT);
- //bind the server socket to port_no and ip
- if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
- {
- perror("Bind failed");
- close(server_socket);
- exit(EXIT_FAILURE);
- }
- //listen for connection
- if (listen(server_socket, 5) < 0)
- {
- perror("Listen failed");
- close(server_socket);
- exit(EXIT_FAILURE);
- }
- printf("server listening\n");
- while(1)
- {
- // accept incomming client
- client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
- if (client_socket < 0)
- {
- perror("Client accept failed");
- continue; // Continue to accept new clients
- }
- //allocate memory for client structure
- client_data_t *data = malloc(sizeof(client_data_t));
- data->client_socket = client_socket;
- data->client_addr = client_addr;
- //create new thread to handle every new client
- if (pthread_create(&thread_id, NULL, handle_client, data) != 0)
- {
- perror("Thread creation failed");
- close(client_socket);
- free(data);
- } else
- {
- //Detach the thread to allow it to clean up automatically after finishing
- pthread_detach(thread_id);
- }
- }
- close(server_socket);
- }
|