this initial multithreaded server doesn't serve anything.
[IRC.git] / Robust / src / Runtime / DSTM / interface / dstmserver.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <pthread.h>
5 #include <netdb.h>
6 #include <fcntl.h>
7 #include "dstmserver.h"
8
9 #define LISTEN_PORT 2153
10 #define BACKLOG 10 //max pending connections
11 #define RECIEVE_BUFFER_SIZE 1500
12
13 void *dstmListen()
14 {
15         int listenfd, acceptfd;
16         struct sockaddr_in my_addr;
17         struct sockaddr_in client_addr;
18         socklen_t addrlength = sizeof(struct sockaddr);
19         pthread_t thread_dstm_accept;
20         int i;
21
22         listenfd = socket(PF_INET, SOCK_STREAM, 0);
23         if (listenfd == -1)
24         {
25                 perror("socket");
26                 exit(1);
27         }
28
29         my_addr.sin_family = AF_INET;
30         my_addr.sin_port = htons(LISTEN_PORT);
31         my_addr.sin_addr.s_addr = INADDR_ANY;
32         memset(&(my_addr.sin_zero), '\0', 8);
33
34         if (bind(listenfd, (struct sockaddr *)&my_addr, addrlength) == -1)
35         {
36                 perror("bind");
37                 exit(1);
38         }
39         
40         if (listen(listenfd, BACKLOG) == -1)
41         {
42                 perror("listen");
43                 exit(1);
44         }
45
46         printf("Listening on port %d, fd = %d\n", LISTEN_PORT, listenfd);
47         while(1)
48         {
49                 acceptfd = accept(listenfd, (struct sockaddr *)&client_addr, &addrlength);
50                 pthread_create(&thread_dstm_accept, NULL, dstmAccept, (void *)acceptfd);
51         }
52         pthread_exit(NULL);
53 }
54
55 void *dstmAccept(void *acceptfd)
56 {
57         int numbytes;
58         char buffer[RECIEVE_BUFFER_SIZE];
59         int fd_flags = fcntl((int)acceptfd, F_GETFD);
60         printf("Recieved connection: fd = %d\n", (int)acceptfd);
61         do
62         {
63                 numbytes = recv((int)acceptfd, (void *)buffer, sizeof(buffer), 0);
64                 buffer[numbytes] = '\0';
65                 if (numbytes == -1)
66                 {
67                         perror("recv");
68                         pthread_exit(NULL);
69                 }
70                 else
71                 {
72                         printf("Read %d bytes from %d\n", numbytes, (int)acceptfd);
73                         printf("%s", buffer);
74                 }
75                 
76         } while (numbytes != 0);
77         if (close((int)acceptfd) == -1)
78         {
79                 perror("close");
80                 pthread_exit(NULL);
81         }
82         else
83                 printf("Closed connection: fd = %d\n", (int)acceptfd);
84         pthread_exit(NULL);
85 }
86
87