-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_server.cpp
74 lines (61 loc) · 1.93 KB
/
http_server.cpp
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
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
const int PORT = 8080; // Port number for the HTTP server
void handle_client(int client_socket) {
const std::string response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 13\r\n"
"\r\n"
"Hello, World!";
// Send the response to the client
send(client_socket, response.c_str(), response.size(), 0);
close(client_socket);
}
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
// Create the server socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
perror("socket");
return 1;
}
// Set up the server address
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY; // Bind to all available interfaces
server_addr.sin_port = htons(PORT);
// Bind the socket to the address
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
close(server_socket);
return 1;
}
// Listen for incoming connections
if (listen(server_socket, 5) < 0) {
perror("listen");
close(server_socket);
return 1;
}
std::cout << "Server listening on port " << PORT << "...\n";
while (true) {
// Accept incoming connections
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket < 0) {
perror("accept");
close(server_socket);
return 1;
}
// Handle the client in a separate function
handle_client(client_socket);
}
close(server_socket);
return 0;
}