-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.cc
99 lines (77 loc) · 2.03 KB
/
server.cc
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
/*
server.cc - General Server Interface
Author: Wenyu "Hearson" Zhang
E-mail: zhangw@purdue.edu
This file is a part of:
Project 3 - Building a HTTP Server
CS290 - System Programming, Fall 2010
Purdue University
For more information, please contact the author.
*/
#include <cstring>
#include <cstdio>
#include <cassert>
#include <cstdlib>
#include "config.h"
#include "server.h"
#include "service.h"
Server::Server() {
_initialized = false;
_masterSocket = -1;
}
Server::~Server() {
stopListen();
}
void Server::initialize(int port, Service *origService, int sizeOfService) {
// Save parameter
_port = port;
_origService = origService;
_sizeOfService = sizeOfService;
_initialized = true;
}
int Server::startListen() {
// Make sure user calls initialize() before listening.
assert( _initialized );
// Initialize sockaddr_in structure
memset( &_serverIP, 0, sizeof( struct sockaddr_in ) );
_serverIP.sin_family = AF_INET;
_serverIP.sin_addr.s_addr = INADDR_ANY;
_serverIP.sin_port = htons( (uint16_t) _port );
// Allocate a socket
if ( (_masterSocket = socket( PF_INET, SOCK_STREAM, 0)) < 0 ) {
perror("socket");
return -1;
}
// Set socket as to reusable.
int socketReusable = 1;
setsockopt( _masterSocket, SOL_SOCKET, SO_REUSEADDR, &socketReusable, sizeof(int));
// Binding socket
if ( bind( _masterSocket, (struct sockaddr *) &_serverIP, sizeof(struct sockaddr)) < 0 ) {
perror("bind");
return -1;
}
// Start listening
if ( listen( _masterSocket, REQUEST_QUEUE_SIZE ) < 0 ) {
perror("listen");
return -1;
}
return 0;
}
void Server::stopListen() {
if (_masterSocket >= 0) {
if ( shutdown(_masterSocket, SHUT_RDWR) < 0 ) {
perror("shutdown");
}
close( _masterSocket );
_masterSocket = -1;
}
}
int Server::callServiceHandler(int sockfd, struct sockaddr_in clientIP ) {
Service* service = _origService->clone();
if (!service) {
perror("Service::clone");
return -1;
}
service->processRequest( sockfd, clientIP );
delete service;
}