-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path034b.c
More file actions
79 lines (63 loc) · 2.12 KB
/
034b.c
File metadata and controls
79 lines (63 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
..........................................................................................................................................
Name : 034b.c
Author : SHRUTI VERMA
Description : Write a program to create a concurrent server.
a. use fork
b. use pthread_create
Date : 30 Sep 2025
..........................................................................................................................................
*/
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/socket.h>
#include<fcntl.h>
#include<netinet/in.h>
#include<pthread.h>
void* handleClient(void* arg) {
int newsockfd = *(int*)arg;
free(arg);
char buffer[1024];
read(newsockfd, buffer, sizeof(buffer));
printf("Client says - %s\n", buffer);
write(newsockfd, "Hello from server!", 19);
close(newsockfd);
return NULL;
}
int main() {
int sockfd, newsockfd;
//create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
//bind to IP/Port
struct sockaddr_in saddr, caddr;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = INADDR_ANY;
saddr.sin_port = htons(8080);
bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
//listen for connections on socket
listen(sockfd, 5);
while(1) {
//accept client on newsocket
socklen_t clen;
clen = sizeof(caddr);
int *newsockfd = malloc(sizeof(int));
*newsockfd = accept(sockfd, (struct sockaddr*)&caddr, &clen);
pthread_t tid;
pthread_create(&tid, NULL, handleClient, newsockfd);
pthread_detach(tid);
}
//close
close(sockfd);
}
/*------------------------------------OUTPUT------------------------------------
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./34b
Client says - Hello Server!!
Client says - Hello Server!!
terminal 2
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./client
Server says : Hello from server!
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./client
Server says : Hello from server!
*/