#include #include #include #include // need this for unix domain sockets. #include // unlink #include #include using namespace std; const string PATH{"/tmp/CalcServer"}; void Send(char op, int socket); void DoMath(char op, int socket); void DoEqual(int socket); void GetResult(int socket); int main() { int theSocket; struct sockaddr_un address, server; string name; theSocket = socket(AF_UNIX, SOCK_STREAM, 0); if(theSocket == -1) { perror("Socket failed: "); exit(1); } memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; strncpy(address.sun_path, PATH.c_str(), sizeof(address.sun_path)-1); // just connect, no bind in this pcase. if( -1 == connect(theSocket,reinterpret_cast( &address), sizeof(struct sockaddr_un))) { perror("Connect failed: "); } bool done{false}; char op; while (not done) { cout << endl; cout << "Enter operation : "; cin >> op; switch(op) { case 'q': Send(op, theSocket); done = true; break; case 'd': done = true; break; case '+': case '-': case '*': case '/': DoMath(op, theSocket); break; case '=': DoEqual(theSocket); break; default: cout << "Plese pick one: q,d,+,-,*,/,=" << endl; break; } } close(theSocket); return 0; } void Send(char op, int socket){ ssize_t bytes = write(socket, &op, sizeof(op)); if (bytes != sizeof(op) ) { cerr << "Write failed" << endl; exit(-1); } } void DoMath(char op, int socket){ // send the operation Send(op, socket); // get the operand int num{0}; cout << "Enter a number " ; cin >> num; cout << endl; // send the operand ssize_t bytes = write(socket, &num, sizeof(num)); if (bytes < sizeof(num)) { cerr << "Write failed " << endl; } GetResult(socket); } const int MSG_SIZE {101}; void DoEqual(int socket){ char buf[MSG_SIZE]; int msg_size; int size; Send('=', socket); read(socket, &size, sizeof(int)); if (size >= MSG_SIZE) { cerr << "Message too large " << endl; } ssize_t bytes = read(socket, buf, size); if (bytes > 0) { buf[bytes] = 0; cout << buf << endl; } GetResult(socket); } void GetResult(int socket){ char buf[MSG_SIZE]; int size; int msg_size; read(socket, &msg_size, sizeof(msg_size)); if (msg_size > MSG_SIZE) { cerr << "Message too large " << endl; } else { ssize_t bytes = read(socket, buf, msg_size); if (bytes > 0) { buf[bytes] = 0; cout << "operation ended with " << buf << endl; } else { cerr << "GetResult failed " << endl; } } }