CITS3002 Computer Networks  
prev
next CITS3002 help3002 CITS3002 schedule  

A Server Process in the Unix Domain (in C)

Now consider our server process which accepts streams of bytes (commands and contents) to be printed on our 3D-printer.

To avoid contention for the printer, and to possibly screen the requests, a single server performs the printing.

#include <many-header-files.h>

int main(int argc, char *argv[])
{
//  ASK OUR OS KERNEL TO ALLOCATE RESOURCES FOR A SOCKET
    int  sd = socket(AF_UNIX, SOCK_STREAM, 0);

    if(sd < 0) {
        perror(argv[0]);     // issue a standard error message
        exit(EXIT_FAILURE);
    }

//  ADVERTISE THE STRING "THREEDsocket" TO THE NEW SOCKET
    if(bind(sd, "THREEDsocket", strlen("THREEDsocket")) != 0) {      
        perror(argv[0]);     // issue a standard error message
        exit(EXIT_FAILURE);
    }

//  ENQUEUE 5 NEW CLIENTS BEFORE REFUSING NEW CONNECTIONS
    listen(sd, 5);

    while(true) {
        struct    sockaddr sockaddr;
        socklen_t          fromlen = sizeof(sockaddr);

//  USE THE 'ADVERTISING' DESCRIPTOR TO ACCEPT NEW CONNECTIONS
        int        newsd   = accept(sd, &sockaddr, &fromlen);

        if(newsd >= 0) {
            read_file_for_printing(newsd);
            shutdown(newsd, SHUT_RDWR);
            close(newsd);
        }
    }
    exit(EXIT_SUCCESS);
    return 0;
}




CITS3002 Computer Networks, Lecture 8, Transport layer protocols and APIs, p16, 24th April 2024.