-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
88 lines (76 loc) · 2.29 KB
/
server.cpp
File metadata and controls
88 lines (76 loc) · 2.29 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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <string>
#include <vector>
#include "imu.h"
int main() {
IMU imu = IMU();
int s = socket(AF_INET, SOCK_STREAM, 0);
if (s == -1) {
std::cout << "Socket creation failed" << std::endl;
std::exit(1);
}
else {
std::cout << "Socket creation successful" << std::endl;
}
struct sockaddr_in sin;
struct in_addr in;
in.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;
sin.sin_port = htons(8000);
sin.sin_addr = in;
if (bind(s, (struct sockaddr *) &sin, sizeof(sockaddr_in)) == -1) {
std::cout << "Socket binding failed" << std::endl;
std::exit(1);
}
else {
std::cout << "Socket binding successful" << std::endl;
}
if (listen(s, 1) == -1) {
std::cout << "Listen failed" << std::endl;
std::exit(1);
}
else {
std::cout << "Listen successful" << std::endl;
}
struct sockaddr_in from;
socklen_t from_len = sizeof(from);
int new_s;
std::string body = "<html><body><h1>Hello, World!</h1></body></html>";
std::string response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: " + std::to_string(body.length()) + "\r\n"
"Connection: close\r\n"
"\r\n"
+ body;
char buf[4096];
std::string receive;
while (true) {
receive = "";
memset(buf, 0, sizeof(buf));
new_s = accept(s, (struct sockaddr *) &from, &from_len);
if (new_s < 0) {
std::cout << "Accept failed" << std::endl;
}
else {
std::cout << "Accept successful" << std::endl;
}
int bytes_read = read(new_s, buf, sizeof(buf));
while (bytes_read > 0) {
receive += buf;
if (strncmp(buf+bytes_read-4, "}}]}", 4) == 0) {
std::cout << std::endl << std::endl << buf << std::endl << std::endl;
break;
}
memset(buf, 0, sizeof(buf));
bytes_read = read(new_s, buf, sizeof(buf));
}
imu.update(receive);
ssize_t bytes_sent = write(new_s, response.c_str(), response.length());
}
};