server.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <arpa/inet.h>
  6. #include<pthread.h>
  7. #define PORT 8081
  8. #define BUFFER_SIZE 1024
  9. void* thread_fun(void* n) {
  10. char buffer[100];
  11. int read_size = 0;
  12. int sockfd = *(int*)n;
  13. printf("Inside thread function\n");
  14. while(1)
  15. {
  16. read_size = read(sockfd, buffer, sizeof(buffer) - 1);
  17. if (read_size < 0) {
  18. perror("Read error");
  19. } else if (read_size == 0) {
  20. printf("Client disconnected\n");
  21. } else {
  22. buffer[read_size] = '\0';
  23. printf("Received data: %s\n", buffer);
  24. }
  25. }
  26. close(sockfd);
  27. return NULL;
  28. }
  29. int main() {
  30. int server_fd, new_socket;
  31. struct sockaddr_in address;
  32. int opt = 1;
  33. int addrlen = sizeof(address);
  34. char buffer[BUFFER_SIZE] = {0};
  35. pthread_t t1;
  36. // Creating socket file descriptor
  37. if ((server_fd = socket(AF_INET, SOCK_STREAM, 0))< 0) {
  38. perror("Socket failed");
  39. exit(EXIT_FAILURE);
  40. }
  41. // Setting up the address structure
  42. address.sin_family = AF_INET;
  43. address.sin_addr.s_addr = INADDR_ANY; // Accept connections from any IP
  44. address.sin_port = htons(PORT);
  45. // Binding the socket to the port
  46. if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
  47. perror("Bind failed");
  48. exit(EXIT_FAILURE);
  49. }
  50. if (listen(server_fd, 3) < 0) {
  51. perror("Listen");
  52. exit(EXIT_FAILURE);
  53. }
  54. printf("Server listening on port %d\n", PORT);
  55. while(1)
  56. {
  57. if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
  58. perror("Accept");
  59. exit(EXIT_FAILURE);
  60. }
  61. printf("server connected to client\n");
  62. //pthread_t t1;
  63. pthread_create(&t1,NULL,thread_fun,&new_socket);
  64. }
  65. pthread_detach(t1);
  66. }