#include "util.c"

int main(void)
{
    int serverfd;
    int fd1, fd2;
    struct sockaddr_in addr;
    int addrlen;

    // Establish Connection
    addr.sin_family = AF_INET;
    addr.sin_port = htons(5342);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    catchError(serverfd = cs461_socket(PF_INET, SOCK_STREAM, 0), -1, "socket");
    catchError(cs461_bind(serverfd, &addr, sizeof(addr)), -1, "bind");
    catchError(cs461_listen(serverfd, 2), -1, "listen");

    catchError(fd1 = cs461_accept(serverfd, &addr, &addrlen), -1, "accept");
    printf("connection 1 established\n");
  
    // Perform Read/Write Tests
    doRecv(fd1);
    doSend(fd1);
    doSend(fd1);
    doRecv(fd1);

    printf("connection 1 only tests completed\n");

    fd2 = accept(serverfd, &addr, &addrlen);
    printf("connection 2 established\n");

    doRecv(fd2);
    doSend(fd2);
    doSend(fd2);
    doRecv(fd2);

    printf("connection 2 only tests completed\n");

    doSend(fd1);
    doSend(fd2);
    doRecv(fd1);
    doRecv(fd2);
    doSend(fd1);
    doSend(fd2);
    doRecv(fd1);
    doRecv(fd2);

    printf("joint connection 1 & 2 tests completed\n");

    // Teardown Connection
    catchError(cs461_close(serverfd), -1, "server socket close");
    catchError(cs461_close(fd1), -1, "1st client close");
    catchError(cs461_close(fd2), -1, "2nd client close");
    return 0;
}
