-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.cc
111 lines (100 loc) · 2.52 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
100
101
102
103
104
105
106
107
108
109
110
111
#include "server.h"
Server::Server() {
// setup variables
buflen_ = 1024;
buf_ = new char[buflen_+1];
}
Server::~Server() {
delete buf_;
}
void
Server::run() {
// create and run the server
create();
serve();
}
void
Server::create() {
}
void
Server::close_socket() {
}
void
Server::serve() {
// setup client
int client;
struct sockaddr_in client_addr;
socklen_t clientlen = sizeof(client_addr);
// accept clients
while ((client = accept(server_,(struct sockaddr *)&client_addr,&clientlen)) > 0) {
handle(client);
}
close_socket();
}
void
Server::handle(int client) {
// loop to handle all requests
while (1) {
// get a request
string request = get_request(client);
// break if client is done or an error occurred
if (request.empty())
break;
// send response
bool success = send_response(client,request);
// break if an error occurred
if (not success)
break;
}
close(client);
}
string
Server::get_request(int client) {
string request = "";
// read until we get a newline
while (request.find("\n") == string::npos) {
int nread = recv(client,buf_,1024,0);
if (nread < 0) {
if (errno == EINTR)
// the socket call was interrupted -- try again
continue;
else
// an error occurred, so break out
return "";
} else if (nread == 0) {
// the socket is closed
return "";
}
// be sure to use append in case we have binary data
request.append(buf_,nread);
}
// a better server would cut off anything after the newline and
// save it in a cache
return request;
}
bool
Server::send_response(int client, string response) {
// prepare to send response
const char* ptr = response.c_str();
int nleft = response.length();
int nwritten;
// loop to be sure it is all sent
while (nleft) {
if ((nwritten = send(client, ptr, nleft, 0)) < 0) {
if (errno == EINTR) {
// the socket call was interrupted -- try again
continue;
} else {
// an error occurred, so break out
perror("write");
return false;
}
} else if (nwritten == 0) {
// the socket is closed
return false;
}
nleft -= nwritten;
ptr += nwritten;
}
return true;
}