// This will not run (properly) under MSDOS

// Header files

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream.h>


// Server application using sockets

int main ()
{
    // Create and initialize the socket

    int sid = socket(AF_UNIX, SOCK_STREAM, 0);

    struct sockaddr sa;

    sa.sa_family = AF_UNIX;
    strcpy(sa.sa_data, "prime");
    bind(sid, &sa, sizeof(sa.sa_family) + sizeof("prime"));

    listen(sid, 3);

    cout << "Server: listening to requests..." << endl;

  // Serve requests

    for (;;) {

        // Accept a new connection

        int cid = accept(sid, NULL, NULL);

        cout << endl << "Server: accepted connection" << endl;

        // Receive a request

        int number;

        recv(cid, &number, sizeof(number), 0);
        cout << "Server: received, isprime(" << number << ") ?" << endl;

        // Request dependent calculation

        int prime = (number % 2) != 0;

        for (int i=3; prime && i*i <= number; i+=2)
            prime = number % i != 0;

        // Send the result

        cout << "Server: sending, isprime(" << number << ") = "
             << (prime ? "true" : "false") << endl;
        send(cid, &prime, sizeof(prime), 0);

        // Shut down the connection

        cout << "Server: shuting down the connection" << endl;
        shutdown(cid, 2);
    }

    // Close the socket

    cout << "Server: closing the socket" << endl;
    close(sid);

    return 0;
}
