Blame view

examples/unix/unechosvr.cpp 1.83 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/unix_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::unix_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
  {
  	int n;
  	char buf[512];
  
  	while ((n = sock.read(buf, sizeof(buf))) > 0)
  		sock.write_n(buf, n);
  
  	cout << "Connection closed" << endl;
  }
  
  // --------------------------------------------------------------------------
  // The main thread runs the UNIX 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 Unix-domain 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
36
37
38
39
  
  	string path = "/tmp/unechosvr.sock";
  
  	if (argc > 1) {
  		path = argv[1];
  	}
  
18a2dbfb   Peter M. Groen   Fixed paths
40
41
  	osdev::components::socket-cpp::socket_initializer sockInit;
  	osdev::components::socket-cpp::unix_acceptor acc;
48b4c725   Peter M. Groen   Setting up Socket-pp
42
  
18a2dbfb   Peter M. Groen   Fixed paths
43
  	bool ok = acc.open(osdev::components::socket-cpp::unix_address(path));
48b4c725   Peter M. Groen   Setting up Socket-pp
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
  
  	if (!ok) {
  		cerr << "Error creating the acceptor: " << acc.last_error_str() << endl;
  		return 1;
  	}
      cout << "Acceptor bound to address: '" << acc.address() << "'..." << endl;
  
  	while (true) {
  		// Accept a new client connection
  		auto sock = acc.accept();
  		cout << "Received a connection" << 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;
  }