-
Notifications
You must be signed in to change notification settings - Fork 0
/
listen_messages.c
109 lines (87 loc) · 2.67 KB
/
listen_messages.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
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
//#include <unistd.h>
#include <string.h>
#include "communication.h"
#include "defines.h"
extern int global_port;
int doSelect(int sock)
{
//for select function:
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
// printf("$");fflush(stdout);
return select(sock+1, &set, NULL, NULL, &timeout);
}
void *listen_messages(void *x_void_ptr)
{
int sockfd, newsockfd, clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
fprintf( stderr, "[%d]RM _STARTING SERVER SOCKET_ ERROR opening socket\n", get_clock() );
exit(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(global_port); //port defined in main.h
/* Now bind the host address using bind() call.*/
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
fprintf( stderr, "[%d]RM _STARTING SERVER SOCKET_ ERROR on binding\n", get_clock() );
exit(1);
}
/* Now start listening for the clients, here
* process will go in sleep mode and will wait
* for the incoming connection
*/
listen(sockfd,5);
clilen = sizeof(cli_addr);
int test=0;
while (1)
{
test = doSelect(sockfd);
if( test < 0 )
{
fprintf( stderr, "[%d]RM[%d] BIG ERROR on accept\n", get_clock , newsockfd );
exit(1);
}
if( test == 0 )
{
sleep(1);
continue;
}
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
printf("[%d]RM[%d] Connection started port: %d \n", get_clock(), newsockfd, global_port);
if (newsockfd < 0 || test < 0)
{
fprintf( stderr, "[%d]RM[%d] ERROR on accept\n", get_clock , newsockfd );
exit(1);
}
/* this variable is our reference to the second thread */
pthread_t process_thread;
/* create a receive data struct to sent to thread. Thread frees this data */
receive_thread_data * rd = malloc(sizeof(receive_thread_data));
rd->sockfd = newsockfd;
rd->ip = cli_addr.sin_addr.s_addr;
rd->port = ntohs(cli_addr.sin_port);
/* execute in separate thread */
if(pthread_create(& process_thread, NULL, receive_message, rd)) {
fprintf(stderr, "[%d]RM[%d] Error creating thread\n", get_clock(), newsockfd );
exit(1);
}
} /* end of while */
return NULL;
}