Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> // cout
- #include <stdlib.h> // exit
- #include <string.h> // bzero
- #include <unistd.h> // close
- #include <stdlib.h>
- #include <time.h>
- #include <set> // library to use sets
- #include <sstream>
- #include "pthread.h"
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <map>
- #include <postgresql/libpq-fe.h>
- #include <algorithm>
- #include <cstdlib>
- #include <arpa/inet.h>
- using namespace std;
- map<string, int> sockets;
- map<int, string> usernames;
- map<string,int>::iterator it;
- map<string, int> game;
- map<string,int> players;
- map<int,string> maximum;
- map<string, int> turn;
- map<string,int> word;
- map<string,int> find_word;
- map<string,int> trys;
- set<int> client_id;
- set<int> started;
- set<int>::iterator it1;
- pthread_mutex_t mutex, mutex1;
- PGconn* conn = NULL; // The database connection
- bool shut_d = false;
- // initializes the database connection
- void initDB()
- {
- conn = PQconnectdb("host='dbm.fe.up.pt' user='sinf17a42' password='aah.hangman' dbname='sinf17a42' port='5432'");
- if (!conn)
- {
- cout << "Failed to connect to the database" << endl;
- exit(-1);
- }
- if (PQstatus(conn) != CONNECTION_OK)
- {
- cout << "Failed to connect to the database" << endl;
- exit(-1);
- }
- }
- // execute a query
- PGresult* executeSQL(string sql)
- {
- PGresult* res = PQexec(conn, sql.c_str());
- if (!(PQresultStatus(res) == PGRES_COMMAND_OK || PQresultStatus(res) == PGRES_TUPLES_OK)){
- cout << "Failed to execute the command: " << sql << endl;
- cout << PQresultErrorMessage(res) << '\n';
- return NULL;
- }
- return res;
- }
- // close the database connection when the server stops
- void closeDB(){
- PQfinish(conn);
- }
- string int_to_string(int i){
- std::stringstream ss;
- ss << i;
- std::string str = ss.str();
- return str;
- }
- int string_to_int(string s){
- int i;
- istringstream iss(s);
- iss >> i;
- return i;
- }
- bool writeline(int socketfd, int originfd, string line, int option){ //option 0 - "client X said...." , option 1 - write a line in a single client
- string tosend;
- if(!option){
- tosend = "Client " + int_to_string(originfd) + " said: " + line + "\n";
- write(socketfd, tosend.c_str(), tosend.size());
- }
- else if(option)
- write(socketfd, line.c_str(), line.size());
- return true;
- }
- bool readline(int socketfd, string &line) {
- int n;
- /* buffer with 1025 positions so we have space
- for the string ending \0 character*/
- char buffer[1025];
- /* initialized the string */
- line = "";
- /* While we don't reach the end of the string
- keep reading */
- while (line.find('\n') == string::npos) {
- // n haracters were read. if == 0 we reached the end of the string
- n = read(socketfd, buffer, 1024);
- if (n == 0) return false;
- buffer[n] = 0; // put a \0 in the end of the buffer
- line += buffer; // add the read text to the string
- }
- // Remove the \r\n
- line.erase(line.end() - 1);
- line.erase(line.end() - 1);
- return true;
- }
- string time_date(int socketfd){
- time_t seconds = time(NULL);
- struct tm * timeinfo = localtime(&seconds);
- ostringstream oss_date,oss_hours;
- oss_date << (timeinfo->tm_year + 1900) << "-" << (timeinfo->tm_mon + 1) << "-" << timeinfo->tm_mday << endl;
- oss_hours << timeinfo->tm_hour << ":" << timeinfo->tm_min << ":" << timeinfo->tm_sec << endl;
- string date1 = oss_date.str();
- string date2 = oss_hours.str();
- string date = date1 + date2;
- return date;
- }
- void broadcast(int originfd, string line, int option){
- for(it1 = client_id.begin(); it1 != client_id.end(); it1++){
- int socketfd = *it1;
- if(socketfd != originfd)
- writeline(socketfd, originfd, line, option);
- }
- }
- bool private_chat(int socketfd, int originfd, string line){
- string tosend;
- int n=0;
- PGresult* res = executeSQL("SELECT * FROM hangman.users WHERE users.username = ('" + line + "')");
- for (int row = 0; row < PQntuples(res); row++){
- if(sizeof(PQgetvalue(res, row, 4)) != 0 && usernames.find(socketfd) != usernames.end()){
- n++;
- tosend = "message: ";
- writeline(originfd,originfd,tosend,1);
- readline(originfd, line);
- line = "User " + usernames[originfd] + " send you this private message: " + line + "\n";
- writeline(socketfd, socketfd, line, 1);
- break;
- }
- if(sizeof(PQgetvalue(res, row, 4)) != 0 && usernames.find(socketfd) == usernames.end()){
- tosend = "User not connected.\n";
- writeline(originfd,originfd,tosend,1);
- return false;
- }
- }
- if(!n){
- tosend = "(?)Invalid username. Try again.\n";
- writeline(originfd,originfd,tosend,1);
- return false;
- }
- return false;
- }
- bool client_logout(int socketfd){
- string tosend;
- if(usernames.find(socketfd) == usernames.end()){
- tosend = "(?)Error doing logout!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- if(players.count(usernames[socketfd])){
- tosend = "(?)End your game first.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- if(usernames.find(socketfd) != usernames.end()){
- sockets.erase(usernames[socketfd]);
- usernames.erase(socketfd);
- tosend = ">> Successful logout!\n";
- writeline(socketfd,socketfd,tosend,1);
- return true;
- }
- return false;
- }
- bool sign_in(int socketfd){
- int n = 0;
- string tosend, tosend_user, tosend_pass;
- if(usernames.find(socketfd) != usernames.end()){
- tosend = "(?)You already have sign in.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- tosend = ">> Username: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,tosend_user);
- if(sockets.find(tosend_user) != sockets.end()){
- tosend = "(?)Access denied. You already have sign in other socket.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- PGresult* res = executeSQL("SELECT * FROM hangman.users WHERE users.username = ('" + tosend_user + "')");
- for (int row = 0; row < PQntuples(res); row++){
- if(sizeof(PQgetvalue(res, row, 4)) != 0){
- n++;
- break;
- }
- }
- if(!n){
- tosend = "(?)Invalid username. Try again!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- n = 0;
- tosend = ">> Password: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,tosend_pass);
- PGresult* res1 = executeSQL("SELECT * FROM hangman.users WHERE users.password = ('" + tosend_pass + "')");
- for (int row = 0; row < PQntuples(res1); row++){
- if(sizeof(PQgetvalue(res1, row, 5)) != 0){
- n++;
- tosend = "Successful login \n";
- writeline(socketfd,socketfd,tosend,1);
- sockets[tosend_user] = socketfd;
- usernames[socketfd] = tosend_user;
- return true;
- }
- }
- if(!n){
- tosend = "(?)Invalid password. Try again!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- return false;
- }
- bool ver_admin(int socketfd){
- PGresult* res = executeSQL("SELECT username FROM hangman.users WHERE admin = 'true'");
- for (int row = 0; row < PQntuples(res); row++){
- if(PQgetvalue(res,row,0) == usernames[socketfd])
- return true;
- }
- return false;
- }
- bool insert_into_users(int socketfd, int i){
- string userinfo[i], tosend;
- tosend = "First name: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,userinfo[0]);
- tosend = "Last name: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,userinfo[1]);
- tosend = "Usernaname: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,userinfo[2]);
- tosend = "Password: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,userinfo[3]);
- userinfo[4] = "true";
- PGresult* res = executeSQL("SELECT * FROM hangman.users WHERE users.username = ('" + userinfo[2] + "')");
- if(PQntuples(res) != 0){
- string tosend = "Username already exists. Try again\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- PGresult* id = executeSQL("SELECT * FROM hangman.users");
- executeSQL("INSERT INTO hangman.users VALUES ('" + int_to_string(PQntuples(id) + 1) + "', '" + userinfo[0] + "', '" + userinfo[1] + "', '" + userinfo[2] + "', '" + userinfo[3] + "', '" + userinfo[4] + "', '0')");
- tosend = "Done!\n";
- writeline(socketfd,socketfd,tosend,1);
- return true;
- }
- bool insert_into_categorys(int socketfd){
- string catinfo, tosend;
- tosend = ">> Category: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,catinfo);
- PGresult* res = executeSQL("SELECT * FROM hangman.category WHERE category.name = ('" + catinfo + "')");
- if(PQntuples(res) != 0){
- string tosend = "Category already exists. Try again\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- PGresult* id = executeSQL("SELECT * FROM hangman.category");
- executeSQL("INSERT INTO hangman.category VALUES ('" + int_to_string(PQntuples(id) + 1) + "', '" + catinfo + "')");
- tosend = ">> Done!\n";
- writeline(socketfd,socketfd,tosend,1);
- return true;
- }
- bool insert_into_words(int socketfd){
- int n = 0;
- string wordinfo, catinfo, tosend;
- tosend = ">> Word: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,wordinfo);
- tosend = ">> Category: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,catinfo);
- PGresult* res = executeSQL("SELECT * FROM hangman.word WHERE word.name = ('" + wordinfo + "')");
- PGresult* result = executeSQL("SELECT * FROM hangman.category WHERE category.name = ('" + catinfo + "')");
- if(PQntuples(res) != 0){
- tosend = "Word already exists. Try again\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- if(!PQntuples(result)){
- tosend = "Insert a valid category. If you want to create a new one write \\category. \n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- PGresult* res1 = executeSQL("SELECT * FROM hangman.category");
- for(int row = 0; row < PQntuples(res1) ; row++){
- if(PQgetvalue(res1,row,1) != catinfo)
- n++;
- else
- break;
- }
- PGresult* id = executeSQL("SELECT * FROM hangman.word");
- executeSQL("INSERT INTO hangman.word VALUES ('" + int_to_string(PQntuples(id) + 1) + "', '" + wordinfo + "', '" + int_to_string(n+1) + "')");
- tosend = ">> Done!\n";
- writeline(socketfd,socketfd,tosend,1);
- return true;
- }
- bool info_user(int socketfd,int originfd,string line){
- string tosend, c_w;
- int n = 0;
- PGresult* res = executeSQL("SELECT score FROM hangman.users WHERE users.username = ('" + line + "')");
- for (int row = 0; row < PQntuples(res); row++){
- if(sizeof(PQgetvalue(res, row, 4)) != 0){
- n++;
- c_w = PQgetvalue(res,0,0);
- tosend = ">> User " + line + " have " + c_w + " wins.\n";
- writeline(originfd,originfd,tosend,1);
- break;
- }
- }
- if(!n){
- tosend = "(?)Invalid username. Try again.\n";
- writeline(originfd,originfd,tosend,1);
- return false;
- }
- return true;
- }
- bool online_users(int socketfd){
- string tosend;
- int n = 0;
- if (sockets.find(usernames[socketfd]) != sockets.end()){
- tosend = "-> Users online:";
- writeline(socketfd,socketfd,tosend,1);
- for(it = sockets.begin(); it != sockets.end(); it++)
- cout << ".........." <<it->first << '-' << (int&)it->second;
- for(it = sockets.begin(); it != sockets.end(); it++){
- if(n == 0){
- tosend = ">> " + it->first + "\n";
- writeline(socketfd,socketfd,tosend,1);
- }
- else if (n != 0){
- tosend = ">> " + it->first + "\n";
- writeline(socketfd,socketfd,tosend,1);
- }
- n++;
- }
- if(!n){
- tosend = " ---None---. \n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- return true;
- }
- else{
- tosend = "(?)Error. Need to login first.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- }
- bool client_off(int socketfd){
- players.erase(usernames[socketfd]);
- turn.erase(usernames[socketfd]);
- sockets.erase(usernames[socketfd]);
- usernames.erase(socketfd);
- close(socketfd);
- return true;
- }
- bool stdwn(){
- for(it1 = client_id.begin(); it1 != client_id.end(); it1++){
- int socketfd = *it1;
- close(socketfd);
- }
- shut_d = true;
- return true;
- }
- int new_game(int socketfd){
- int c, nr_trys = 7;
- int n = 0;
- string tosend, word1, under_ = "", category;
- if(usernames.find(socketfd) == usernames.end()){
- tosend = "(?)You have to login first.\n";
- writeline(socketfd,socketfd,tosend,1);
- return 0;
- }
- if(players.count(usernames[socketfd])){
- tosend = "(?)End your game first.\n";
- writeline(socketfd,socketfd,tosend,1);
- return 0;
- }
- string cat = "", max, wordid;
- tosend = ">> Number max of players: ";
- writeline(socketfd, socketfd, tosend, 1);
- readline(socketfd,max);
- tosend = ">> Choose the category (optional): ";
- writeline(socketfd, socketfd, tosend, 1);
- readline(socketfd,cat);
- PGresult* res3 = executeSQL("SELECT * FROM hangman.word");
- if(cat == ""){
- PGresult* res = executeSQL("SELECT * FROM hangman.word ORDER BY random() LIMIT 1");
- word1 = PQgetvalue(res,0,1);
- for(int row1 = 0; row1 < PQntuples(res3) ; row1++){
- if(PQgetvalue(res3,row1,1) == word1){
- category = PQgetvalue(res3,row1,2);
- wordid = PQgetvalue(res3,row1,0);
- break;
- }
- }
- c = 0;
- }
- else{
- PGresult* res1 = executeSQL("SELECT * FROM hangman.category WHERE category.name = ('" + cat + "')");
- if(PQntuples(res1) == 0){
- string tosend = "Category doesn't exists. Try again.\n";
- writeline(socketfd,socketfd,tosend,1);
- return 0;
- }
- PGresult* res2 = executeSQL("SELECT * FROM hangman.category");
- for(int row = 0; row < PQntuples(res2) ; row++){
- if(PQgetvalue(res2,row,1) != cat)
- n++;
- else
- break;
- }
- category = int_to_string(n+1);
- PGresult* result = executeSQL("SELECT * FROM hangman.word WHERE word.idcat = " + category + " ORDER BY random() LIMIT 1");
- word1 = PQgetvalue(result,0,1);
- for(int row =0; row < PQntuples(result) ; row++){
- if(PQgetvalue(result,row,1) == word1){
- wordid = PQgetvalue(result,row,0);
- break;
- }
- }
- c = 1;
- }
- for(size_t i = 0; i < word1.size(); ++i)
- under_ = under_ + '_';
- cout << word1 << endl;
- int i_max = string_to_int(max);
- PGresult* id = executeSQL("SELECT * FROM hangman.game");
- tosend = ">> Modes -> hard - H / easy - E: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,tosend);
- if(!tosend.find("H"))
- trys[int_to_string(PQntuples(id) + 1)] = nr_trys;
- else
- trys[int_to_string(PQntuples(id) + 1)] = 1000;
- cout << under_ << " " << word1 << endl;
- game[int_to_string(PQntuples(id) + 1)] = string_to_int(max) - 1;
- maximum[i_max] = int_to_string(PQntuples(id) + 1);
- players[usernames[socketfd]] = PQntuples(id) + 1;
- word[word1] = PQntuples(id) + 1;
- find_word[under_] = PQntuples(id) + 1;
- string begin = time_date(socketfd);
- executeSQL("INSERT INTO hangman.game VALUES ('" + int_to_string(PQntuples(id) + 1) + "', 'NULL','" + usernames[socketfd] + "','" + begin + "','" + " NULL','" + category + "','" + wordid + "')");
- tosend = ">> Game with id " + int_to_string(PQntuples(id) + 1) + " created! Waiting for players.\n";
- writeline(socketfd,socketfd,tosend,1);
- if(c)
- tosend = ">> Created a new game for " + max + " players in the " + cat + " category with id " + int_to_string(PQntuples(id) + 1) + "\n";
- else
- tosend = ">> Created a new game for " + max + " players with id " + int_to_string(PQntuples(id) + 1) + "\n";
- cout << tosend << endl;
- broadcast(socketfd,tosend, 1);
- return (PQntuples(id) + 1);
- }
- bool join_game(int socketfd, int id){
- string tosend;
- if(players.count(usernames[socketfd])){
- tosend = "(?)You cannot join another game.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- if(!game.count(int_to_string(id))){
- tosend = "(?)Game doesn't exists.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- it = game.find(int_to_string(id));
- if((int&)it->second == 0){
- tosend = "(?)Game is full!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- else{
- players[usernames[socketfd]] = id;
- int max = (int&)it->second - 1;
- game[int_to_string(id)] = max;
- if (max != 0){
- tosend = ">> " + int_to_string(max) + " players left to close the game with id " + int_to_string(id) + ".\n";
- broadcast(socketfd,tosend,1);
- writeline(socketfd,socketfd,tosend,1);
- }
- else if(max == 0){
- tosend = ">> The game with id is " + int_to_string(id) + " is close. The game is ready to start.\n";
- cout << ">> The game with id is " << id << " is close. The game is already to start." << endl;
- broadcast(socketfd,tosend,1);
- writeline(socketfd,socketfd,tosend,1);
- }
- tosend = ">> Successful join! Please, wait for the game.\n";
- writeline(socketfd,socketfd,tosend,1);
- return true;
- }
- }
- bool end_game(int id_game){
- for(it = game.begin(); it != game.end(); it++){
- if(string_to_int(it->first) == id_game){
- game.erase(it->first);
- maximum.erase(it->second);
- }
- }
- for(it = word.begin(); it != word.end(); it++){
- if(it->second == id_game)
- word.erase(it->first);
- }
- for(it = find_word.begin(); it != find_word.end(); it++){
- if(it->second == id_game)
- find_word.erase(it->first);
- }
- for(it = turn.begin(); it != turn.end(); it++){
- if(players[it->first] == id_game){
- turn.erase(it->first);
- players.erase(it->first);
- }
- }
- return true;
- }
- int test_guess(int socketfd, string line){
- string tosend;
- int id_game = players[usernames[socketfd]], n = 0, num;
- it = trys.find(int_to_string(id_game));
- num = it->second;
- trys[int_to_string(id_game)] = num - 1;
- if(!num)
- return 3;
- string wrd, unk_wrd;
- for(it = word.begin(); it != word.end(); it++){
- if(it->second == id_game)
- wrd = it->first;
- }
- for(it = find_word.begin(); it != find_word.end(); it++){
- if(it->second == id_game){
- unk_wrd = it->first;
- break;
- }
- }
- string new_wrd = unk_wrd;
- find_word.erase(unk_wrd);
- it = find_word.find(unk_wrd);
- if(line.size() == sizeof(char)){
- char letter = line[0];
- for(size_t i = 0; i < wrd.size(); i++){
- if(letter == wrd[i] && unk_wrd[i] == 95){
- new_wrd[i] = letter;
- n++;
- }
- }
- find_word[new_wrd] = id_game;
- if(new_wrd == wrd)
- return 2;
- else if(n != 0){
- tosend = ">> Good. Letter " + line + " exists. Continue.\n";
- writeline(socketfd,socketfd,tosend,1);
- return 1;
- }
- else{
- tosend = ">> Wrong. Letter " + line + " doesn't exist.\n";
- writeline(socketfd,socketfd,tosend,1);
- return 0;
- }
- }
- else{
- if(line == wrd){
- find_word[line] = id_game;
- return 2;
- }
- else{
- tosend = ">> Wrong. Word " + line + " doesn't match.\n";
- writeline(socketfd,socketfd,tosend,1);
- find_word[unk_wrd] = id_game;
- return 0;
- }
- }
- return 0;
- }
- bool start_game(int id, int socketfd){
- string tosend;
- if(!game.count(int_to_string(id))){
- tosend = "(?)Game doesn't exists.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- if(started.count(id)){
- tosend = ">> Game has already started!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- if(!players.count(usernames[socketfd])){
- tosend = "(?)You don't belong to that game. Try to join first!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- it = players.find(usernames[socketfd]);
- if(it->first == usernames[socketfd] && it->second != id){
- tosend = "(?)You don't belong to that game. Try to join first!\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- tosend = ">> Game has started. Good luck!\n";
- for(it = players.begin(); it != players.end(); it++){
- if(it->first == usernames[socketfd] && (int&)it->second == id){
- turn[it->first] = 1;
- writeline(sockets[it->first],sockets[it->first],tosend,1);
- }
- else if(it->first != usernames[socketfd] && (int&)it->second == id){
- turn[it->first] = 0;
- writeline(sockets[it->first],sockets[it->first],tosend,1);
- }
- }
- started.insert(id);
- tosend = ">> Player " + usernames[socketfd] + " to guess.\n";
- for(it = players.begin(); it != players.end(); it++){
- if(it->second == id && it->first != usernames[socketfd])
- writeline(sockets[it->first],sockets[it->first],tosend,1);
- }
- tosend = ">> It's your turn.\n";
- writeline(socketfd,socketfd,tosend,1);
- for(it = find_word.begin(); it != find_word.end(); it++){
- if(it->second == id){
- tosend = "word: " + it->first + "\n";
- writeline(socketfd,socketfd,tosend,1);
- break;
- }
- }
- return true;
- }
- bool update_db(int socketfd, int id_game){
- string score;
- executeSQL("UPDATE hangman.game SET winner = '" + usernames[socketfd] + "' WHERE idgame = " + int_to_string(id_game));
- string end = time_date(socketfd);
- executeSQL("UPDATE hangman.game SET end_hours = '" + end + "' WHERE idgame = " + int_to_string(id_game));
- PGresult* res = executeSQL("SELECT username, score FROM hangman.users");
- for(int row = 0; row < PQntuples(res); row++){
- if(PQgetvalue(res, row, 0) == usernames[socketfd]){
- int aux = string_to_int(PQgetvalue(res,row,1)) + 1;
- score = int_to_string(aux);
- break;
- }
- }
- executeSQL("UPDATE hangman.users SET score = " + score + " WHERE username = '" + usernames[socketfd] + "'");
- return true;
- }
- bool turns(int socketfd){
- int b;
- string tosend, save;
- int id_game = players[usernames[socketfd]], n = 0;
- for(it = turn.begin(); it != turn.end(); it++){
- if(it->first == usernames[socketfd])
- n++;
- if(it->first == usernames[socketfd] && it->second == 0){
- tosend = ">> Wait for your turn.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- else if(it->first == usernames[socketfd] && it->second == 1)
- break;
- }
- if(!n){
- tosend = "(?)You aren't playing.\n";
- writeline(socketfd,socketfd,tosend,1);
- return false;
- }
- tosend = "letter/word: ";
- writeline(socketfd,socketfd,tosend,1);
- readline(socketfd,tosend);
- b = test_guess(socketfd,tosend);
- if(b == 3){
- tosend = "(!)Number of tries exceeded. Try again latter!\n";
- for(it = players.begin(); it != players.end(); it++){
- if(it->second == id_game)
- writeline(sockets[it->first],sockets[it->first],tosend,1);
- }
- end_game(id_game);
- return false;
- }
- for(it = players.begin(); it != players.end(); it++){
- if(it->first != usernames[socketfd] && it->second == id_game){
- string tosend_guess = ">> "+ usernames[socketfd] + " guessed **" + tosend + "**\n";
- writeline(sockets[it->first],sockets[it->first],tosend_guess,1);
- }
- }
- it = find_word.find(usernames[socketfd]);
- string wrd;
- for(it = find_word.begin(); it != find_word.end(); it++){
- if(it->second == id_game)
- wrd = it->first;
- }
- it = players.find(usernames[socketfd]);
- if(b == 2){
- tosend = ">> You won! Congratilations!!!\n";
- writeline(socketfd,socketfd,tosend,1);
- for(it = players.begin(); it != players.end(); it++){
- if(it->first != usernames[socketfd] && it->second == id_game){
- tosend = ">> Player " + usernames[socketfd] + " won! The word was: " + wrd + "\n";
- writeline(sockets[it->first],sockets[it->first],tosend,1);
- }
- }
- end_game(id_game);
- update_db(socketfd,id_game);
- return true;
- }
- else if(b == 0){
- turn[it->first] = 0;
- while(1){
- if(it == players.end())
- it = players.begin();
- else
- it++;
- if(it->second == id_game){
- turn[it->first] = 1;
- it->first;
- save = it->first;
- break;
- }
- }
- }
- else if(b == 1)
- save = it->first;
- for(it = find_word.begin(); it != find_word.end(); it++){
- if(it->second == id_game){
- tosend = "-> word: " + it->first + "\n";
- writeline(socketfd,socketfd,tosend,1);
- break;
- }
- }
- tosend = ">> It's your turn.\n";
- writeline(sockets[save],sockets[save],tosend,1);
- for(it = find_word.begin(); it != find_word.end(); it++){
- if(it->second == id_game){
- tosend = "-> word: " + it->first + "\n";
- writeline(sockets[save],sockets[save],tosend,1);
- break;
- }
- }
- for(it = players.begin(); it != players.end(); it++){
- if(it->first != save && it->second == id_game){
- tosend = ">> Player " + save + " to guess. \n";
- writeline(sockets[it->first],sockets[it->first],tosend,1);
- }
- }
- return true;
- }
- bool commands(int originfd, string line){
- string tosend, max, cat;
- writeline(originfd, originfd, tosend, 1);
- if(!line.find("\\help")){
- tosend = "escrever ajudas \n";
- writeline(originfd, originfd, tosend, 1);
- }
- else if(!line.find("\\login"))
- sign_in(originfd);
- else if(!line.find("\\register"))
- insert_into_users(originfd,6);
- else if(!line.find("\\users_on"))
- online_users(originfd);
- else if(!line.find("\\logout"))
- client_logout(originfd);
- else if(!line.find("\\chat")){
- if (usernames.find(originfd) != usernames.end()){
- tosend = ">> What username that you want to chat?\n";
- writeline(originfd,originfd,tosend,1);
- readline(originfd, line);
- private_chat(sockets[line],originfd,line);
- }
- else{
- tosend = "(?)To chat you have to login. \n";
- writeline(originfd,originfd,tosend,1);
- }
- }
- else if(!line.find("\\category")){
- if (usernames.find(originfd) == usernames.end()){
- tosend = "(?)Try again. Need to login first.\n";
- writeline(originfd, originfd, tosend, 1);
- }
- else if(ver_admin(originfd) == false){
- tosend = "(?)Only administrators can add categorys.\n";
- writeline(originfd, originfd, tosend, 1);
- }
- else
- insert_into_categorys(originfd);
- }
- else if(!line.find("\\word")){
- if(usernames.find(originfd) == usernames.end()){
- tosend = "(?)Try again. Need to login first.\n";
- writeline(originfd,originfd,tosend,1);
- }
- else if(ver_admin(originfd) == false){
- tosend = "(?)Only administrators can add words.\n";
- writeline(originfd, originfd, tosend, 1);
- }
- else
- insert_into_words(originfd);
- }
- else if(!line.find("\\new")){
- if(usernames.find(originfd) == usernames.end()){
- tosend = "(?)Try again. Need to login first.\n";
- writeline(originfd,originfd,tosend,1);
- }
- else
- new_game(originfd);
- }
- else if(!line.find("\\join")){
- if(usernames.find(originfd) == usernames.end()){
- tosend = "(?)Try again. Need do login first\n";
- writeline(originfd,originfd,tosend,1);
- }
- else{
- tosend = ">> What is the ID of the game? ";
- writeline(originfd,originfd,tosend,1);
- readline(originfd,tosend);
- if(started.count(string_to_int(tosend))){
- tosend = "(?)Game has already started!\n";
- writeline(originfd,originfd,tosend,1);
- return false;
- }
- else
- join_game(originfd,string_to_int(tosend));
- }
- }
- else if(!line.find("\\start")){
- if (usernames.find(originfd) != usernames.end()){
- tosend = "-> Id of the game: ";
- writeline(originfd,originfd,tosend,1);
- readline(originfd,tosend);
- int id = string_to_int(tosend);
- start_game(id,originfd);
- }
- else{
- tosend = "(?)Error. Need to login first.\n";
- writeline(originfd,originfd,tosend,1);
- }
- }
- else if(!line.find("\\guess")){
- if (usernames.find(originfd) != usernames.end())
- turns(originfd);
- else{
- tosend = "(?)Error. Need to login first.\n";
- writeline(originfd,originfd,tosend,1);
- }
- }
- else if(!line.find("\\info_user")){
- if (usernames.find(originfd) != usernames.end()){
- tosend = "-> What username that you want to know informations?\n";
- writeline(originfd,originfd,tosend,1);
- readline(originfd, line);
- info_user(sockets[line],originfd,line);
- }
- else{
- tosend = "(?)Error. Need to login first.\n";
- writeline(originfd,originfd,tosend,1);
- }
- }
- else if(!line.find("\\exit")){
- client_off(originfd);
- cout << ">> Client " << originfd << " disconnects.\n";
- }
- else if(!line.find("\\shutdown"))
- if (usernames.find(originfd) != usernames.end() && ver_admin(originfd) == true)
- stdwn();
- else if(usernames.find(originfd) != usernames.end() && ver_admin(originfd) == false){
- tosend = "(?)Error. Only administrators can shutdown.\n";
- writeline(originfd,originfd,tosend,1);
- }
- else{
- tosend = "(?)Error. Need do login first.\n";
- writeline(originfd,originfd,tosend,1);
- }
- else{
- cout << ">> Socket " << originfd << " said: " << line << endl;
- broadcast(originfd,line,0);
- }
- return true;
- }
- // handles one client
- void* client(void* args){
- int sockfd = *(int*)args;
- string line, tosend;
- pthread_mutex_lock(&mutex);
- client_id.insert(sockfd);
- pthread_mutex_unlock(&mutex);
- cout << "Reading from socket " << sockfd << endl;
- tosend = "To see the commands write 'info'.\n";
- writeline(sockfd, sockfd, tosend, 1);
- while (readline(sockfd, line)){
- if(!line.find("info")){
- tosend = "for HELP - \\help\nto login - \\login\nto sign up - \\register\nto se online users - \\users_on\nto do logout - \\logout\nto send a message to a client - \\chat\nto add a new category - \\category\nto add a new word - \\word (don't forget to choose the category)\nto creat a new game - \\new\nto join to a created game - \\join\nto start a new game - \\start\nto play - \\guess\nto know nr of wins of a player - \\info_user\nto disconnect - \\exit\nto shutdown the server and all the clients - \\shutdown (only administrators)\n";
- writeline(sockfd, sockfd, tosend, 1);
- }
- else
- commands(sockfd,line);
- if(shut_d == true)
- exit(-1);
- }
- cout << "Closing socket " << sockfd << endl;
- client_id.erase(sockfd);
- close(sockfd);
- return 0;
- }
- int main()
- {
- initDB();
- /* Data structures */
- int sockfd, newsockfd, port = 2002;
- socklen_t client_addr_length;
- struct sockaddr_in serv_addr, cli_addr;
- /* Initialize the socket
- AF_INET - We are using IP
- SOCK_STREAM - We are using TCP
- sockfd - id of the main server socket
- If it returns < 0 an error occurred */
- sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if (sockfd < 0) {
- cout << "Error creating socket" << endl;
- exit(-1);
- }
- /* Create the data structure that stores the server address
- bzero - cleans the structure
- AF_INET - IP address
- INADDR_ANY - Accept request from any IP address */
- bzero((char *) &serv_addr, sizeof(serv_addr));
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_addr.s_addr = INADDR_ANY;
- serv_addr.sin_port = htons(port);
- sockfd = socket(AF_INET , SOCK_STREAM , 0);
- struct sockaddr_in server;
- server.sin_addr.s_addr = inet_addr("127.0.0.1");
- server.sin_family = AF_INET;
- server.sin_port = htons(port);
- int res = connect(sockfd , (struct sockaddr *)&server , sizeof(server));
- int yes=1;
- if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes) == -1) {
- perror("setsockopt");
- exit(1);
- }
- /* Bind the socket. The socket is now active but we
- are still not receiving any connections
- If it returns < 0 an error occurred */
- res = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
- if (res < 0) {
- cout << "Error binding to socket" << endl;
- exit(-1);
- }
- /* Start listening to connections. We want to have
- at most 5 pending connections until we accept them */
- listen(sockfd, 5);
- while (true){
- /* Accept a new connection. The client address is stored as:
- cli_addr - client address
- newsockfd - socket id for this client */
- client_addr_length = sizeof(cli_addr);
- if(shut_d == true)
- break;
- else
- newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &client_addr_length);
- /* Create a thread to handle this client */
- pthread_t thread1;
- pthread_mutex_init(&mutex,NULL);
- pthread_create(&thread1, NULL, client, &newsockfd);
- pthread_mutex_destroy(&mutex);
- }
- /* Close the server socket */
- close(sockfd);
- closeDB();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement