Example #1
0
Client::Client()
{
    connect(this,SIGNAL(readyRead()),this,SLOT(readMessage()));
    connect(logic,SIGNAL(gameStart()),this,SIGNAL(readyToStart()));
    connect(logic,SIGNAL(sendCommand(QString)),this,SLOT(sendMessage(QString)));
    connect(this,SIGNAL(getMessage(QString)),logic,SLOT(getCommand(QString)));
    logic->setClient(this);
}
Example #2
0
void SocketHandler::HandleSuccessConnection(Message2 message)
{
    QJsonObject obj = Network2::ParseJson(message);

    qDebug() << obj["map"];
    qDebug() << obj["your_id"];

    map_ = obj["map"].toString();

    QJsonValue val = obj["your_id"];
    your_id_ = val.toVariant().toInt();

    emit readyToStart(your_id_, map_);
}
Example #3
0
ClientUI::ClientUI(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ClientUI)
{
    tcpSocket=new Client;
    ui->setupUi(this);
//    QRegExp regAddr("[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}");
//    ui->addr->setValidator(new QRegExpValidator(regAddr, this));
    QRegExp regPort("[0-9]{1,6}");
    ui->port->setValidator(new QRegExpValidator(regPort, this));
    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(link()));
    connect(ui->cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
    connect(ui->startButton, SIGNAL(clicked()), this, SLOT(accept()));
    connect(tcpSocket,SIGNAL(readyToStart()),this,SLOT(startGame()));
    connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),
             this,SLOT(displayError(QAbstractSocket::SocketError)));

    ui->addr->setText("127.0.0.1");
    //ui->addr->setText("2001:5C0:1000:B::7C63");
    ui->port->setText("50000");
}
Example #4
0
void TcpServer::incomingConnection(qintptr socketDescriptor) {

    if (threadPool.size() < maxConnections) {
        QThread *thread = new QThread;
        Client *client = new Client(socketDescriptor);
        client->moveToThread(thread);

        connect(thread, SIGNAL(started()), client, SLOT(run()));

        connect(client, SIGNAL(newGame(QString, QString, QList<QString>)),this,SLOT(newGame(QString, QString, QList<QString>)));
        connect(client, SIGNAL(startGame(QString)),this,SLOT(readyToStart(QString)));
        connect(this, SIGNAL(sendData(QList<QPair<QString,Snake*> >,QList<Food*>)), client, SLOT(sendData(QList<QPair<QString,Snake*> >,QList<Food*>)));

        connect(this, SIGNAL(transmit(Client*,QList<QString>)), client, SLOT(transmit(Client*,QList<QString>)));

        connect(client, SIGNAL(changeDirect(int,QString)), this, SLOT(setDirect(int,QString)));
        connect(client, SIGNAL(disconnected(Client*)), this, SLOT(removeClient(Client*)));
        connect(this, SIGNAL(endOfGame(QString,QString)), client, SLOT(gameOver(QString,QString)));                  //end of the game

        thread->start();

        WRITELOCK(threadPool.insert(client,thread));
    }
int KCupsConnection::renewDBusSubscription(int subscriptionId, int leaseDuration, const QStringList &events)
{
    int ret = -1;

    if (!readyToStart()) {
        kWarning() << "Tryied to run on the wrong thread";
        return subscriptionId; // This is not intended to be used in the gui thread
    }

    ipp_t *response = NULL;
    do {
        ipp_t *request;
        ipp_op_e operation;

        // check if we have a valid subscription ID
        if (subscriptionId >= 0) {
            // Add the "notify-events" values to the request
            operation = IPP_RENEW_SUBSCRIPTION;
        } else {
            operation = IPP_CREATE_PRINTER_SUBSCRIPTION;
        }

        // Lets create the request
        request = ippNewRequest(operation);
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI,
                     KCUPS_PRINTER_URI, NULL, "/");
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                     "requesting-user-name", NULL, cupsUser());

        if (operation == IPP_CREATE_PRINTER_SUBSCRIPTION) {
            // Add the "notify-events" values to the request
            QVariantHash values;
            values["notify-events"] = events;
            requestAddValues(request, values);

            ippAddString(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_KEYWORD,
                         "notify-pull-method", NULL, "ippget");
            ippAddString(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_URI,
                         "notify-recipient-uri", NULL, "dbus://");
            ippAddInteger(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
                          "notify-lease-duration", leaseDuration);
        } else {
            ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_INTEGER,
                          "notify-subscription-id", subscriptionId);
            ippAddInteger(request, IPP_TAG_SUBSCRIPTION, IPP_TAG_INTEGER,
                          "notify-lease-duration", leaseDuration);
        }

        // Do the request
        response = cupsDoRequest(CUPS_HTTP_DEFAULT, request, "/");
    } while (retry("/"));

#ifdef HAVE_CUPS_1_6
    if (response && ippGetStatusCode(response) == IPP_OK) {
#else
    if (response && response->request.status.status_code == IPP_OK) {
#endif // HAVE_CUPS_1_6
        ipp_attribute_t *attr;
        if (subscriptionId >= 0) {
            // Request was ok, just return the current subscription
            ret = subscriptionId;
        } else if ((attr = ippFindAttribute(response,
                                            "notify-subscription-id",
                                            IPP_TAG_INTEGER)) == NULL) {
            kWarning() << "No notify-subscription-id in response!";
            ret = -1;
        } else {
#ifdef HAVE_CUPS_1_6
            ret = ippGetInteger(attr, 0);
        }
    } else if (subscriptionId >= 0 && response && ippGetStatusCode(response) == IPP_NOT_FOUND) {
        kDebug() << "Subscription not found";
        // When the subscription is not found try to get a new one
        return renewDBusSubscription(-1, leaseDuration, events);
#else
            ret = attr->values[0].integer;
        }
    } else if (subscriptionId >= 0 && response && response->request.status.status_code == IPP_NOT_FOUND) {
        kDebug() << "Subscription not found";
        // When the subscription is not found try to get a new one
        return renewDBusSubscription(-1, leaseDuration, events);
#endif // HAVE_CUPS_1_6
    } else {
        kWarning() << "Request failed" << lastError();
        // When the server stops/restarts we will have some error so ignore it
        ret = subscriptionId;
    }

    ippDelete(response);

    return ret;
}
ReturnArguments KCupsConnection::request(ipp_op_e operation,
                                         const char *resource,
                                         const QVariantHash &reqValues,
                                         bool needResponse)
{
    ReturnArguments ret;

    if (!readyToStart()) {
        return ret; // This is not intended to be used in the gui thread
    }

    ipp_t *response = NULL;
    bool needDestName = false;
    int group_tag = IPP_TAG_PRINTER;
    do {
        ipp_t *request;
        bool isClass = false;
        QString filename;
        QVariantHash values = reqValues;

        ippDelete(response);

        if (values.contains(QLatin1String("printer-is-class"))) {
            isClass = values.take(QLatin1String("printer-is-class")).toBool();
        }
        if (values.contains(QLatin1String("need-dest-name"))) {
            needDestName = values.take(QLatin1String("need-dest-name")).toBool();
        }
        if (values.contains(QLatin1String("group-tag-qt"))) {
            group_tag = values.take(QLatin1String("group-tag-qt")).toInt();
        }

        if (values.contains(QLatin1String("filename"))) {
            filename = values.take(QLatin1String("filename")).toString();
        }

        // Lets create the request
        if (values.contains(QLatin1String(KCUPS_PRINTER_NAME))) {
            request = ippNewDefaultRequest(values.take(QLatin1String(KCUPS_PRINTER_NAME)).toString(),
                                           isClass,
                                           operation);
        } else {
            request = ippNewRequest(operation);
        }

        // send our user name on the request too
        ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
                     "requesting-user-name", NULL, cupsUser());

        // Add the requested values to the request
        requestAddValues(request, values);

        // Do the request
        // do the request deleting the response
        if (filename.isEmpty()) {
            response = cupsDoRequest(CUPS_HTTP_DEFAULT, request, resource);
        } else {
            response = cupsDoFileRequest(CUPS_HTTP_DEFAULT, request, resource, filename.toUtf8());
        }
    } while (retry(resource));

    if (response != NULL && needResponse) {
        ret = parseIPPVars(response, group_tag, needDestName);
    }
    ippDelete(response);

    return ret;
}
int main(int args, char *argv[]) {

	char message[100];
	MainPlayerData toPlayerData;
	CandidateData toCandidateData;
	StatusType status;
	fd_set allSocket;
	fd_set readfds;
	int fdmax, k, l;
	int n;
	int playerIndex;
	int mainPlayerSelected = 0;
	int clientId;
	int playerAnswer;
	int level;
	int numberOfClient = 0;
	int yes = 1;
	int readResult;
	int listener;
	int acceptSocket;
	struct sockaddr_in server, client;
	int sin_size;
	int socket_in_allSocket;
	int nbytes;
	int i, j;
	char clientName[40];
	initializeClientList();
	createCashPrizeList();
	sin_size = sizeof(struct sockaddr_in);
	FD_ZERO(&allSocket);
	FD_ZERO(&readfds);
	if (args < 2) {
		printf("Usage : %s <PORT>\n", argv[0]);
		exit(-1);
	}
	readResult = readQuestionFile("question.txt");
	if (readResult < 0) {
		printf("Can't load the questions !");
		exit(-1);
	}
	if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		printf("socket() error!\n");
		exit(-1);
	}
	server.sin_family = AF_INET;
	server.sin_port = htons(atoi(argv[1]));
	server.sin_addr.s_addr = INADDR_ANY;
	bzero(&(server.sin_zero), 8);
	setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
	if (bind(listener, (struct sockaddr*) &server, sizeof(struct sockaddr))
			== -1) {
		printf("bind() error!\n");
		exit(-1);
	}
	//listen
	if (listen(listener, 2) == -1) {
		perror("listen");
		exit(3);
	}
	FD_SET(listener, &allSocket);
	fdmax = listener;
	printf("\t<<<Gameshow GHE NONG - AI LA TRIEU PHU>>>\n");
	while (1) {

		readfds = allSocket;

		/* On error, -1 is returned, select() and pselect() return the number of file descriptors */
		if (mainPlayerSelected == 0) {
			if (select(fdmax + 1, &readfds, NULL, NULL, NULL ) == -1) {
				perror("select");
				printf("errno = %d.\n", errno);
				exit(4);
			}
		}

		for (i = 0; i <= fdmax; i++) {

			if (FD_ISSET(i, &readfds)) {
				//printf("isset i=%d\n", i);
				if (i == listener) {

					acceptSocket = accept(listener, (struct sockaddr*) &client,
							&sin_size);
					printf("Listener : %d accept %d\n", listener, acceptSocket);
					//in dia chi ip
					printf("\n client address %s\n",
							inet_ntoa(client.sin_addr));
					if (acceptSocket == -1) {
						perror("accept");

					} else if (isClientListFull()) {
						clientId = NULL_ID;
						send(acceptSocket, &clientId, sizeof clientId, 0);
						close(acceptSocket);
						//FD_CLR(acceptSocket, &allSocket);
					} else {
						FD_SET(acceptSocket, &allSocket);
						printf("Server connected with socket %d\n",
								acceptSocket);
						addClient(acceptSocket);
						clientId = acceptSocket;
						if (acceptSocket > fdmax) {
							fdmax = acceptSocket;
							//printf("Now fdmax is : %d\n", fdmax);
						}
						send(acceptSocket, &clientId, sizeof clientId, 0);
						numberOfClient = getNumberOfClient();
						printf("We're now having %d clients connected !\n",
								numberOfClient);
					}

				} else {
//					printf("i before switch = %d Fmax=%d\n", i, fdmax);
					switch_case: switch (getClientStatus(i)) {
					case CONNECTED:
						if ((nbytes = recv(i, &toCandidateData,
								sizeof toCandidateData, 0)) <= 0) {
							printf(
									"Server stopped connecting to client id %d\n",
									i);
							close(i);
							removeClient(i);
							printf("%d clients left !\n", getNumberOfClient());
							FD_CLR(i, &allSocket);
							break;
						} else {
							recv(i, clientName, sizeof clientName, 0);
							setClientStatus(i, WAITING, clientName);
							strcpy(message, "Welcome : ");
							strcat(message, clientName);
							strcat(message, "\n");
							strcpy(toCandidateData.message, message);
							toCandidateData.status = WAITING;
							send(i, &toCandidateData, sizeof toCandidateData,
									0);
							printClientList();
							/* check if have enough 6 clients, so we can start the game */
							if (readyToStart()) {
								printf("We can start the game !!\n");
								k = randomNumber(NUMBERS_PER_QUES);
								//send question to all the clients //
								for (j = 0; j < BACKLOG; j++) {
									setCompetition(j);
									copyQuestion(&(toCandidateData.question),
											questLib[0][k]);
									toCandidateData.ansTime = 0;
									toCandidateData.status = COMPETING;
									strcpy(toCandidateData.message,
											QUICK_QUESTION_MESSAGE);
									send(clientInfo[j].id, &toCandidateData,
											sizeof(CandidateData), 0);
								}
								//get the answer back from them //
								for (j = 0; j < BACKLOG; j++) {
									if (recv(clientInfo[j].id, &toCandidateData,
											sizeof toCandidateData, 0) <= 0) {
										printf(
												"Server stopped connecting to client id %d\n",
												i);
										close(i);
										removeClient(i);
										printf("%d clients left !\n",
												getNumberOfClient());
										FD_CLR(i, &allSocket);
									} else {
										clientInfo[j].quick_answer =
												toCandidateData.answer;
										clientInfo[j].ansTime =
												toCandidateData.ansTime;
									}
								}
								//printf("Sending question done!\n");
								printClientsAnswerList();
								//select the main player //
								playerIndex = selectMainPlayer(questLib[0][k],
										BACKLOG);
								printf(
										"Our answer for the quick question : %d\n",
										questLib[0][k].ans);
								printf("====MAIN PLAYER SELECTED : %s ====\n",
										clientInfo[playerIndex].clientName);
								printClientStatus(clientInfo[playerIndex].id);
								startGame(playerIndex);

								for (j = 0; j < BACKLOG; j++) {
									if (j != playerIndex) {
										strcpy(toCandidateData.message,
												JOINER_MESSAGE);
									} else {
										strcpy(toCandidateData.message,
												MAIN_PLAYER_SELECTED);
										strcpy(toPlayerData.name,
												clientInfo[j].clientName);
									}
									toCandidateData.status = getClientStatus(
											clientInfo[j].id);
									send(clientInfo[j].id, &toCandidateData,
											sizeof(CandidateData), 0);

								}
								printClientList();
								//printf("Current i = %d\n", i);
								i = clientInfo[playerIndex].id;
								mainPlayerSelected = 1;
								goto switch_case;
//								break;
							} else {
								sprintf(message,
										"We now have %d players online, please wait until we have more %d client(s) !\n",
										getNumberOfClient(),
										BACKLOG - getNumberOfClient());
								strcpy(toCandidateData.message, message);
								send(i, &toCandidateData,
										sizeof toCandidateData, 0);

							}
						}
						break;
					case JOINING:
						//printf("[JOINING] Current i = %d\n", i);
//						i = 0;
//						if (mainPlayerSelected == 1) {
//							if ((nbytes = recv(i, &toCandidateData,
//									sizeof toCandidateData, 0)) <= 0) {
//								printf(
//										"Server stopped connecting to client id %d\n",
//										i);
//								close(i);
//								removeClient(i);
//								printf("%d clients left !\n",
//										getNumberOfClient());
//								FD_CLR(i, &allSocket);
//								break;
//							}
//						}
						break;
					case PLAYING:
						mainPlayerSelected = 1;
						initializeMainPlayerData(&toPlayerData);
						level = 1;
						do {
							selectQuestion(level, &toPlayerData);
							send(clientInfo[playerIndex].id, &toPlayerData,
									sizeof toPlayerData, 0);
							for (n = 0; n < BACKLOG; n++) {
								if (clientInfo[n].status == JOINING) {
									send(clientInfo[n].id, &toPlayerData,
											sizeof toPlayerData, 0);
								}
							}
							if (recv(i, &playerAnswer, sizeof playerAnswer, 0)
									<= 0) {
								printf(
										"Server stopped connecting to client id %d\n",
										i);
								close(i);
								removeClient(i);
								printf("%d clients left !\n",
										getNumberOfClient());
								FD_CLR(i, &allSocket);
								gameFinish(&toPlayerData,END);
								for (n = 0; n < BACKLOG; n++) {
									if (clientInfo[n].status == JOINING) {
										toPlayerData.status = FINISHED;
										send(clientInfo[n].id, &toPlayerData,
												sizeof toPlayerData, 0);
										close(clientInfo[n].id);
										removeClient(clientInfo[n].id);
										FD_CLR(clientInfo[n].id, &allSocket);
									}
								}
								continue;
							}

							if (playerAnswer == RIGHT) {
								printf("Good job! The player gave a right answer!\n");
								increaseQuestion(&toPlayerData);
								//tra loi dung o cau hoi so 15
								if (level == MAX_LEVEL) {
									wonGame(&toPlayerData);
									send(i, &toPlayerData, sizeof toPlayerData,
											0);
									for (n = 0; n < BACKLOG; n++) {
										if (clientInfo[n].status == JOINING) {
											send(clientInfo[n].id,
													&toPlayerData,
													sizeof toPlayerData, 0);
											close(clientInfo[n].id);
											removeClient(clientInfo[n].id);
											FD_CLR(clientInfo[n].id,
													&allSocket);
										}
									}
									close(i);
									removeClient(i);
									FD_CLR(i, &allSocket);
									exit(1);
								}
								level = level + 1;
							} else {
								endGame(&toPlayerData, playerAnswer);
								gameFinish(&toPlayerData,playerAnswer);
								send(i, &toPlayerData, sizeof toPlayerData, 0);
								for (n = 0; n < BACKLOG; n++) {
									if (clientInfo[n].status == JOINING) {
										toPlayerData.status = FINISHED;
										send(clientInfo[n].id, &toPlayerData,
												sizeof toPlayerData, 0);
										close(clientInfo[n].id);
										removeClient(clientInfo[n].id);
										FD_CLR(clientInfo[n].id, &allSocket);
									}
								}
								close(i);
								removeClient(i);
								printf("%d clients left !\n",
										getNumberOfClient());
								FD_CLR(i, &allSocket);
							}
						} while (playerAnswer == RIGHT && level <= MAX_LEVEL);
						printf("The game of player : %s ended !\n",
								toPlayerData.name);
						exit(1);
						break;
					default:
						break;
					}

				}
			}

		}

	}
}