unecho.cpp 1.21 KB
#include <iostream>
#include <string>
#include "socket-cpp/unix_connector.h"
#include "socket-cpp/version.h"

using namespace std;

// --------------------------------------------------------------------------

int main(int argc, char* argv[])
{
	cout << "Sample Unix-domain echo client for 'sockpp' "
		<< osdev::components::socket-cpp::SOCKPP_VERSION << '\n' << endl;

	string path = (argc > 1) ? argv[1] : "/tmp/unechosvr.sock";

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

	osdev::components::socket-cpp::unix_connector conn;

    bool ok = conn.connect(osdev::components::socket-cpp::unix_address(path));
	if (!ok) {
		cerr << "Error connecting to UNIX socket at " << path
			<< "\n\t" << conn.last_error_str() << endl;
		return 1;
	}

	cout << "Created a connection to '" << conn.peer_address() << "'" << endl;

	string s, sret;
	while (getline(cin, s) && !s.empty()) {
		if (conn.write(s) != (int) s.length()) {
			cerr << "Error writing to the UNIX stream" << endl;
			break;
		}

		sret.resize(s.length());
		int n = conn.read_n(&sret[0], s.length());

		if (n != (int) s.length()) {
			cerr << "Error reading from UNIX stream" << endl;
			break;
		}

		cout << sret << endl;
	}

	return (!conn) ? 1 : 0;
}