Blame view

examples/tcp/tcp6echosvr.cpp 1.88 KB
48b4c725   Peter M. Groen   Setting up Socket-pp
1
2
  #include <iostream>
  #include <thread>
18a2dbfb   Peter M. Groen   Fixed paths
3
4
  #include "socket-cpp/tcp6_acceptor.h"
  #include "socket-cpp/version.h"
48b4c725   Peter M. Groen   Setting up Socket-pp
5
6
7
8
9
10
11
12
  
  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.
  
18a2dbfb   Peter M. Groen   Fixed paths
13
  void run_echo(osdev::components::socket-cpp::tcp6_socket sock)
48b4c725   Peter M. Groen   Setting up Socket-pp
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  {
  	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' "
18a2dbfb   Peter M. Groen   Fixed paths
32
  		<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;
48b4c725   Peter M. Groen   Setting up Socket-pp
33
34
35
  
  	in_port_t port = (argc > 1) ? atoi(argv[1]) : 12345;
  
18a2dbfb   Peter M. Groen   Fixed paths
36
37
  	osdev::components::socket-cpp::socket_initializer sockInit;
  	osdev::components::socket-cpp::tcp6_acceptor acc(port);
48b4c725   Peter M. Groen   Setting up Socket-pp
38
39
40
41
42
43
44
45
  
  	if (!acc) {
  		cerr << "Error creating the acceptor: " << acc.last_error_str() << endl;
  		return 1;
  	}
  	cout << "Awaiting connections on port " << port << "..." << endl;
  
  	while (true) {
18a2dbfb   Peter M. Groen   Fixed paths
46
  		osdev::components::socket-cpp::inet6_address peer;
48b4c725   Peter M. Groen   Setting up Socket-pp
47
48
  
  		// Accept a new client connection
18a2dbfb   Peter M. Groen   Fixed paths
49
  		osdev::components::socket-cpp::tcp6_socket sock = acc.accept(&peer);
48b4c725   Peter M. Groen   Setting up Socket-pp
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  		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;
  }