tcp6echosvr.cpp
1.88 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
#include <iostream>
#include <thread>
#include "socket-cpp/tcp6_acceptor.h"
#include "socket-cpp/version.h"
using namespace std;
// --------------------------------------------------------------------------
// The thread function. This is run in a separate thread for each socket.
// Ownership of the socket object is transferred to the thread, so when this
// function exits, the socket is automatically closed.
void run_echo(osdev::components::socket-cpp::tcp6_socket sock)
{
ssize_t n;
char buf[512];
while ((n = sock.read(buf, sizeof(buf))) > 0)
sock.write_n(buf, n);
cout << "Connection closed from " << sock.peer_address() << endl;
}
// --------------------------------------------------------------------------
// The main thread runs the TCP port acceptor. Each time a connection is
// made, a new thread is spawned to handle it, leaving this main thread to
// immediately wait for the next connection.
int main(int argc, char* argv[])
{
cout << "Sample IPv6 TCP echo server for 'sockpp' "
<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;
in_port_t port = (argc > 1) ? atoi(argv[1]) : 12345;
osdev::components::socket-cpp::socket_initializer sockInit;
osdev::components::socket-cpp::tcp6_acceptor acc(port);
if (!acc) {
cerr << "Error creating the acceptor: " << acc.last_error_str() << endl;
return 1;
}
cout << "Awaiting connections on port " << port << "..." << endl;
while (true) {
osdev::components::socket-cpp::inet6_address peer;
// Accept a new client connection
osdev::components::socket-cpp::tcp6_socket sock = acc.accept(&peer);
cout << "Received a connection request from " << peer << endl;
if (!sock) {
cerr << "Error accepting incoming connection: "
<< acc.last_error_str() << endl;
}
else {
// Create a thread and transfer the new stream to it.
thread thr(run_echo, std::move(sock));
thr.detach();
}
}
return 0;
}