server.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include<stdio.h>
  2. #include<arpa/inet.h>
  3. #include<stdlib.h>
  4. #include<unistd.h>
  5. #include<string.h>
  6. #include<pthread.h>
  7. #define port 8081
  8. pthread_t t1;
  9. int i=0;
  10. void* thread_fun(void* n) {
  11. char buffer[100];
  12. int read_size = 0;
  13. int sockfd = *(int*)n;
  14. printf("Inside thread function\n");
  15. while(1)
  16. {
  17. read_size = read(sockfd, buffer, sizeof(buffer) - 1); // Leave space for null terminator
  18. if (read_size < 0) {
  19. perror("Read error");
  20. } else if (read_size == 0) {
  21. printf("Client disconnected\n");
  22. return NULL;
  23. } else {
  24. buffer[read_size] = '\0';
  25. printf("Received data: %s\n", buffer);
  26. }
  27. }
  28. close(sockfd);
  29. return NULL;
  30. }
  31. int main()
  32. {
  33. int sockfd,*newfd;
  34. struct sockaddr_in address;
  35. int addrlen = sizeof(address);
  36. if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
  37. perror("socket failed\n");
  38. address.sin_family = AF_INET;
  39. address.sin_addr.s_addr = INADDR_ANY;
  40. address.sin_port = htons(port);
  41. if((bind(sockfd,(struct sockaddr*)&address,sizeof(address)))<0)
  42. perror("bind failed\n");
  43. if((listen(sockfd,3))<0)
  44. perror("server listening failed\n");
  45. else
  46. printf("server listening\n");
  47. while(1)
  48. {
  49. newfd = malloc(sizeof(int));
  50. *newfd=accept(sockfd,(struct sockaddr*)&address,(socklen_t*)&addrlen);
  51. if(*newfd<0)
  52. {
  53. perror("accept failed\n");
  54. }
  55. else
  56. printf("client connected\n");
  57. if(pthread_create(&t1,NULL,thread_fun,newfd)==0)
  58. printf("new thread created\n");
  59. }
  60. pthread_detach(t1);
  61. }