#include #include #include #include #include #include #define port 8081 pthread_t t1; int i=0; void* thread_fun(void* n) { char buffer[100]; int read_size = 0; int sockfd = *(int*)n; printf("Inside thread function\n"); while(1) { read_size = read(sockfd, buffer, sizeof(buffer) - 1); // Leave space for null terminator if (read_size < 0) { perror("Read error"); } else if (read_size == 0) { printf("Client disconnected\n"); return NULL; } else { buffer[read_size] = '\0'; printf("Received data: %s\n", buffer); } } close(sockfd); return NULL; } int main() { int sockfd,*newfd; struct sockaddr_in address; int addrlen = sizeof(address); if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0) perror("socket failed\n"); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(port); if((bind(sockfd,(struct sockaddr*)&address,sizeof(address)))<0) perror("bind failed\n"); if((listen(sockfd,3))<0) perror("server listening failed\n"); else printf("server listening\n"); while(1) { newfd = malloc(sizeof(int)); *newfd=accept(sockfd,(struct sockaddr*)&address,(socklen_t*)&addrlen); if(*newfd<0) { perror("accept failed\n"); } else printf("client connected\n"); if(pthread_create(&t1,NULL,thread_fun,newfd)==0) printf("new thread created\n"); } pthread_detach(t1); }