forked from agueijo/Internetworking
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcp_server_threads_mutex.c
More file actions
142 lines (91 loc) · 2.19 KB
/
Copy pathtcp_server_threads_mutex.c
File metadata and controls
142 lines (91 loc) · 2.19 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
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
#define P_SIZE sizeof(struct psuma)
struct psuma {
uint16_t v1;
uint16_t v2;
uint32_t res;
};
void *suma (void *);
void *ver_cone (void *);
int leer_mensaje ( int , char * , int );
int cone;
pthread_mutex_t m;
pthread_cond_t c;
int main() {
int lon;
int sd;
int sd_cli;
struct sockaddr_in servidor;
struct sockaddr_in cliente;
pthread_t tid;
pthread_t tid_ver;
servidor.sin_family = AF_INET;
servidor.sin_port = htons (4444);
servidor.sin_addr.s_addr = INADDR_ANY;
sd = socket (PF_INET, SOCK_STREAM, 0);
if ( bind ( sd , (struct sockaddr *) &servidor , sizeof(servidor) ) < 0 ) {
perror("Error en bind\n");
exit (-1);
}
listen ( sd , 5);
cone = 0;
pthread_mutex_init ( &m , NULL);
pthread_cond_init ( &c , NULL);
pthread_create ( &tid_ver, NULL, ver_cone, NULL );
while (1) {
lon = sizeof(cliente);
sd_cli = accept ( sd , (struct sockaddr *) &cliente , &lon);
pthread_mutex_lock (&m);
cone++;
pthread_cond_signal (&c);
pthread_mutex_unlock (&m);
pthread_create ( &tid, NULL, suma, &sd_cli );
}
close (sd);
}
void *suma ( void *arg ) {
int sdc;
int n;
char buffer[P_SIZE];
struct psuma *suma;
suma = (struct psuma *) buffer;
sdc = *( (int *) arg);
n = 1;
while ( n != 0) {
if ( ( n = leer_mensaje ( sdc , buffer , P_SIZE ) ) > 0 ) {
suma->res = htonl ( ntohs (suma->v1) + ntohs(suma->v2) );
printf ("Enviando: %d %d %d \n",ntohs(suma->v1),ntohs(suma->v2),ntohl(suma->res));
send ( sdc , buffer , P_SIZE ,0 );
}
}
close (sdc);
pthread_mutex_lock (&m);
cone--;
pthread_cond_signal (&c);
pthread_mutex_unlock (&m);
}
void *ver_cone (void * arg) {
while (1) {
pthread_mutex_lock (&m);
pthread_cond_wait(&c,&m);
printf("Conexiones %d\n",cone);
pthread_mutex_unlock (&m);
}
}
int leer_mensaje ( int socket , char *buffer , int total ) {
int bytes, leido;
leido = 0;
bytes = 1;
while ( (leido < total) && (bytes > 0) ) {
bytes = recv ( socket , buffer + leido , total - leido , 0 );
leido = leido + bytes;
}
return (leido);
}