123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #include<pthread.h>
- #define PORT 8081
- #define BUFFER_SIZE 1024
- 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);
- if (read_size < 0) {
- perror("Read error");
- } else if (read_size == 0) {
- printf("Client disconnected\n");
- } else {
- buffer[read_size] = '\0';
- printf("Received data: %s\n", buffer);
- }
- }
- close(sockfd);
- return NULL;
- }
- int main() {
- int server_fd, new_socket;
- struct sockaddr_in address;
- int opt = 1;
- int addrlen = sizeof(address);
- char buffer[BUFFER_SIZE] = {0};
- pthread_t t1;
- // Creating socket file descriptor
- if ((server_fd = socket(AF_INET, SOCK_STREAM, 0))< 0) {
- perror("Socket failed");
- exit(EXIT_FAILURE);
- }
- // Setting up the address structure
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY; // Accept connections from any IP
- address.sin_port = htons(PORT);
- // Binding the socket to the port
- if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
- perror("Bind failed");
- exit(EXIT_FAILURE);
- }
- if (listen(server_fd, 3) < 0) {
- perror("Listen");
- exit(EXIT_FAILURE);
- }
- printf("Server listening on port %d\n", PORT);
- while(1)
- {
- if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
- perror("Accept");
- exit(EXIT_FAILURE);
- }
- printf("server connected to client\n");
- //pthread_t t1;
- pthread_create(&t1,NULL,thread_fun,&new_socket);
- }
- pthread_detach(t1);
- }
|