-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
48 lines (36 loc) · 1.11 KB
/
main.cpp
File metadata and controls
48 lines (36 loc) · 1.11 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
/* Echo Server & Client: Create a simple server that receives a message from a client and sends it back.
* This introduces asio::io_context and basic socket handling */
// I'm not even gonna write a client. Just gonna use netcat since i only need to listen and receive a raw
// stream of bytes. No big deal.
#include "pch.hpp"
// a simple macro for managing allocs
#define kb(x) ((x) * 1024)
using asio::ip::tcp;
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Usage: server <port>\n";
return 1;
}
try {
asio::io_context io;
tcp::acceptor acceptor(io, tcp::endpoint(
tcp::v4(), atoi(argv[1]))
); // accepting any connections, since it's bound to 0.0.0.0
for (;;) {
tcp::socket socket(io);
acceptor.accept(socket);
char buffer[kb(1)];
asio::error_code ec;
size_t bytes = socket.read_some(asio::buffer(buffer), ec);
if (!ec) {
std::cout.write(buffer, bytes);
asio::error_code ignored_error;
asio::write(socket,
asio::buffer(buffer, bytes), ignored_error);
}
}
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}