-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.c
145 lines (83 loc) · 2.1 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <pthread.h>
#define PORT 15636
void *thread(void *vargp);
void *threadsend(void *vargp);
void *threadrecv(void *vargp);
void*thread(void *vargp)
{
pthread_t tid1, tid2;
int connfd = *((int *)vargp);
int idata;
char temp[100];
pthread_create(&tid1, NULL, threadsend, vargp);
pthread_create(&tid2, NULL, threadrecv, vargp);
return NULL;
}
void *threadsend(void *vargp)
{
int connfd = *((int *)vargp);
int idata;
char temp[100];
while(1){
fgets(temp, 100, stdin);
send(connfd, temp, 100, 0);
printf(" Server Send OK \n");
}
return NULL;
}
void *threadrecv(void *vargp)
{
char temp[100];
int connfd = *((int *)vargp);
while(1){
int idata = 0;
idata = recv(connfd, temp, 100, 0);
if(idata > 0){
printf("<<Client>>:\n%s\n", temp);
}
}
return NULL;
}
int main()
{
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
if(listenfd < 0){
perror("socket");
exit(1);
}
struct hostent *hp;
struct sockaddr_in serveraddr;
bzero((char *)&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(PORT);
if(bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0){
perror("connect");
exit(1);
}
if(listen(listenfd, 1024) < 0){
perror("listen error");
exit(1);
}
struct sockaddr_in clientaddr;
int clientlen, *connfdp;
clientlen = sizeof(clientaddr);
while(1){
connfdp = (int *)malloc(sizeof(int));
*connfdp = accept(listenfd, (struct sockaddr *)&clientaddr, &clientlen);
pthread_t tid;
printf("Accepted!\n");
pthread_create(&tid, NULL, thread, connfdp);
}
return EXIT_SUCCESS;
}