-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_client_server.c
59 lines (57 loc) · 1.46 KB
/
multi_client_server.c
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#define PORT 8000
#define MAXSZ 100
int main()
{
int sockfd;
int newsockfd;
struct sockaddr_in servaddr;
struct sockaddr_in clientaddr;
int n;
char msg[MAXSZ];
int cli_len;
int pid;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(sockfd, 5);
while (1)
{
printf("\nServer waiting for new client connection:\n");
cli_len = sizeof(clientaddr);
newsockfd = accept(sockfd, (struct sockaddr *)&clientaddr, &cli_len);
printf("connected to client:%s\n", inet_ntoa(clientaddr.sin_addr));
pid = fork();
if (pid == 0)
{
while (1)
{
n = recv(newsockfd, msg, MAXSZ, 0);
if (n == 0)
{
close(newsockfd);
break;
}
msg[n] = 0;
send(newsockfd, msg, n, 0);
printf("Receive and set:%s\n", msg);
}
exit(0);
}
else
{
close(newsockfd);
}
}
return 0;
}