unechosvr.cpp 1.83 KB
#include <iostream>
#include <thread>
#include "socket-cpp/unix_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::unix_socket sock)
{
	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' "
		<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;

	string path = "/tmp/unechosvr.sock";

	if (argc > 1) {
		path = argv[1];
	}

	osdev::components::socket-cpp::socket_initializer sockInit;
	osdev::components::socket-cpp::unix_acceptor acc;

	bool ok = acc.open(osdev::components::socket-cpp::unix_address(path));

	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;
}