Survey Server
#include <iostream>
#include <fstream>
#include <pthread.h>
#include "PracticalSocket.h"
#include "SurveyCommon.h"
 
using namespace std;
 
static vector<Question> qList;
static pthread_mutex_t lock;
static vector<vector<int> > rCount;
 
static void *conductSurvey(void *arg);
 
int main(int argc, char *argv[]) {
    if (argc != 2) {
        cerr << "Usage: SurveyServer <Survey File>" << endl;
        return 1;
    }
 
    ifstream input(argv[1]);
    if (!input || !readSurvey(input, qList)) {
        cerr << "Can't read survey from file: " << argv[1] << endl;
        return 1;
    }
 
    for (unsigned int i = 0; i < qList.size(); i++)
        rCount.push_back(vector<int>(qList[i].rList.size(), 0));
    pthread_mutex_init(&lock, NULL);
 
    try {
        TCPServerSocket servSock(SURVEY_PORT);
 
        for (;;) {               // run infinite loop to accept clients
            TCPSocket *sock = servSock.accept();
 
            pthread_t newThread;               // for every client, create a thread
            if (pthread_create(&newThread, NULL, conductSurvey, sock) != 0) {
                cerr << "Can't create new thread" << endl;
                delete sock;
            }
        }
    } catch (SocketException &e) {
        cerr << e.what() << endl;
    }
 
    return 0;
}
 
static void *conductSurvey(void *arg) {
    TCPSocket *sock = (TCPSocket *) arg;
    try {
        sendInt(sock, qList.size());
 
        for (unsigned int q = 0; q < qList.size(); q++) {
            sendString(sock, qList[q].qText);
            sendInt(sock, qList[q].rList.size());
            for (unsigned int r = 0; r < qList[q].rList.size(); r++)
                sendString(sock, qList[q].rList[r]);
 
            unsigned int response = recvInt(sock);
            if (response >= 0 && response < rCount[q].size()) {
                pthread_mutex_lock(&lock);               // mutex lock
                rCount[q][response]++;
                pthread_mutex_unlock(&lock);           // mutex unlock
            }
        }
    } catch (runtime_error e) {
        cerr << e.what() << endl;
    }
 
    delete sock;
    return NULL;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License