-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.h
More file actions
165 lines (104 loc) · 3.52 KB
/
server.h
File metadata and controls
165 lines (104 loc) · 3.52 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#ifndef SERVER_H
#define SERVER_H
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include "requests.h"
#include "response.h"
using namespace std;
#define PORT 8080
#define BUFFER_SIZE 1024
class Server{
public:
int server_fd;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
int CreateServer(){
server_fd = socket(AF_INET , SOCK_STREAM, 0);
if (server_fd == -1){
return 1;
};
return 0;
};
Server(){
address.sin_family = AF_INET;
address.sin_port = htons(PORT);
address.sin_addr.s_addr = INADDR_ANY;
if(CreateServer() == 1){
cerr << "Failed to create socket\n";
exit(1);
}
else{
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
cerr << "Binding failed\n";
exit(1);
};
};
if (listen(server_fd, 3) < 0) {
perror("Listen failed");
exit(1);
};
cout << "Listening on port " << PORT << endl;
};
void Run(){
while (true){
clientStruct.client_socket = accept(server_fd , (struct sockaddr*)&address , (socklen_t*)&addrlen);
if(clientStruct.client_socket < 0){
cerr << "Accept failed\n";
exit(1);
};
read(clientStruct.client_socket , buffer, BUFFER_SIZE);
cout << "Received request: \n" << buffer << endl;
setRequest(buffer);
if(req.method == "GET") {
for(const auto &pair : setget) {
if(pair.first == req.url)
{
pair.second(req);
};
};
}
else if(req.method == "POST"){
for(const auto &pair : setpost) {
if(pair.first == req.url)
{
pair.second(req);
};
};
}
else if(req.method == "PUT"){
for(const auto &pair : setput) {
if(pair.first == req.url)
{
pair.second(req);
};
};
}
else if(req.method == "PATCH"){
for(const auto &pair : setpatch) {
if(pair.first == req.url)
{
pair.second(req);
};
};
}
else if(req.method == "DELETE"){
for(const auto &pair : setdel) {
if(pair.first == req.url)
{
pair.second(req);
};
};
}
else{
cout << "Method not allowed";
};
close(clientStruct.client_socket);
};
};
};
#endif