Soy totalmente nuevo en desarrollo, así que entiendo que mi código puede ser absolutamente incorrecto. Pero tengo un problema al conectar el segundo cliente en el servidor. Encontré un error con la función de aceptación. Cuando intento conectar el segundo cliente, mi programa deja de funcionar, el servidor espera a los datos del segundo cliente, pero no puedo enviar datos. Intenté usar WSAGetLastError (), pero devuelve 0. Por favor, ayúdame. Es mi servidor:

# include <iostream>
# include <WinSock2.h>
# pragma comment(lib,"ws2_32.lib")
class tictac {
   char garr[10];
public:
   tictac() {garr[0]='0'; for(int i=0; i<10;++i){garr[i]=garr[0]+i;}}
   void move(int turn, char field_change) {
       garr[turn]=field_change;
   }
   char chack(int chack) {
       if(garr[chack]=='O'||garr[chack]=='X') {
            return 'B';
       } else {
            return 'U';
       }
   }
} ;
class play {

    tictac OurGame;

    SOCKADDR_IN playerTurn1;
    SOCKADDR_IN playerTurn2;

    SOCKET playerSock1;
    SOCKET playerSock2;

public:

    int play1(){
     WSAData game_one;
    if((WSAStartup(MAKEWORD(2,2), &game_one))!=0) {
        std::cout<<"Filed to init socket library. Code : "<<WSAGetLastError()<<std::endl;
        system ("pause");
        return 1;
    }
    SOCKET serverSocket = socket(2,1,6);
        if(serverSocket==INVALID_SOCKET) {
            std::cout<<"Fail to create socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 2;
        }
        SOCKADDR_IN serverGame;
        serverGame.sin_family=2;
        serverGame.sin_port=htons(4324);
        serverGame.sin_addr.s_addr=INADDR_ANY;
        if(bind(serverSocket, (sockaddr*)&serverGame,sizeof(serverGame))!=0) {
            std::cout<<"Fail to bind socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 3;
        }
        listen(serverSocket, 5);

        ///////////////////////////////////////////////////////////////////////////////////////////////////
        playerTurn1;
        serverGame.sin_family=2;
        serverGame.sin_port=htons(4324);
        serverGame.sin_addr.s_addr=inet_addr("127.0.0.1");
        //////////////////////////////////////////////////////////////////////////////////////////////////

        int size1=sizeof(playerTurn1);
        playerSock1 = accept(serverSocket, (sockaddr*)& playerTurn1, &size1);   // Socket of first player
                if(playerSock1==INVALID_SOCKET) {
                    std::cout<<"Failed accept with player 1. Code : "<<WSAGetLastError()<<std::endl;
                    system ("pause");
                    return 4;
                }


                char msg[2]="y";
                int turn;
                while(msg[0]!='Y'){
                    // =================================    ******* ******* ****** Turn of player one
                recv(playerSock1, msg, 2, 0);
                std::cout<<msg[0]<<std::endl;
                turn=atoi(&msg[0]);
                    if(turn==0||OurGame.chack(turn)=='B') {
                        msg[0]='N';
                        send(playerSock1, msg, 2, 0);
                        std::cout<<"fail"<<std::endl;
                } else {
                    msg[0]='Y';
                    OurGame.move(turn, 'X');
                    send(playerSock1, msg, 2, 0);
                    }
                }

                if(closesocket(serverSocket)==SOCKET_ERROR) {std::cout<<"ERROR With closing server socket !"<<std::endl; }
                if(closesocket(playerSock1)==SOCKET_ERROR) { std::cout<<"ERROR With closing player's socket !"<<std::endl;}
                system ("pause");
                WSACleanup();
    }

    int play2() {
       WSAData game_two;
    if((WSAStartup(MAKEWORD(2,2), &game_two))!=0) {
        std::cout<<"Filed to init socket library. Code : "<<WSAGetLastError()<<std::endl;
        system ("pause");
        return 1;
    }
    SOCKET serverSocket = socket(2,1,6);
        if(serverSocket==INVALID_SOCKET) {
            std::cout<<"Fail to create socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 2;
        }
        SOCKADDR_IN serverGame;
        serverGame.sin_family=2;
        serverGame.sin_port=htons(4324);
        serverGame.sin_addr.s_addr=INADDR_ANY;
        if(bind(serverSocket, (sockaddr*)&serverGame,sizeof(serverGame))!=0) {
            std::cout<<"Fail to bind socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 3;
        }
        listen(serverSocket, 5);

        ///////////////////////////////////////////////////////////////////////////////////////////////////
        playerTurn2;
        serverGame.sin_family=2;
        serverGame.sin_port=htons(4324);
        serverGame.sin_addr.s_addr=inet_addr("127.0.0.1");
        //////////////////////////////////////////////////////////////////////////////////////////////////

        int size2=sizeof(playerTurn2);
        playerSock1 = accept(serverSocket, (sockaddr*)& playerTurn1, &size2);   // Socket of second player
        std::cout<<"I beg of you, say me something!"<<std::endl; system ("pause");
                if(playerSock1==INVALID_SOCKET) {
                    std::cout<<"Failed accept with player 1. Code : "<<WSAGetLastError()<<std::endl;
                    system ("pause");
                    return 4;
                }


                char msg[2]="y";
                int turn;
                while(msg[0]!='Y'){
                    // =================================    ******* ******* ****** Turn of player one
                recv(playerSock1, msg, 2, 0);
                std::cout<<msg[0]<<std::endl;
                turn=atoi(&msg[0]);
                    if(turn==0||OurGame.chack(turn)=='B') {
                        msg[0]='N';
                        send(playerSock1, msg, 2, 0);
                        std::cout<<"fail"<<std::endl;
                } else {
                    msg[0]='Y';
                    OurGame.move(turn, 'X');
                    send(playerSock1, msg, 2, 0);
                    }
                }

                if(closesocket(serverSocket)==SOCKET_ERROR) {std::cout<<"ERROR With closing server socket !"<<std::endl; }
                if(closesocket(playerSock1)==SOCKET_ERROR) { std::cout<<"ERROR With closing player's socket !"<<std::endl;}
                system ("pause");
                WSACleanup();

    }

} ;
int main() {
      play PlayGame;
      int queue=0;
      while(true){
          if(queue%2==0){
              std::cout<<"first player"<<std::endl;
          PlayGame.play1();
          ++queue;
          } else {
                std::cout<<"Second player"<<std::endl;
          PlayGame.play2();
          ++queue;
          }
      }
}

Es mi primer cliente:

# include <iostream>
# include <WinSock2.h>
# pragma comment(lib,"ws2_32.lib")
class Game {
    char cell[9];
public:
    Game() {cell[0]='1'; for(int i=0; i<9; ++i){cell[i]=cell[0]+i;}}
    void board() {  // ==================== =======================   * * * This method just prints start game board
        char table[3][3];
        int index=0;
        std::cout<<"   GAME BOARD"<<std::endl<<std::endl;
        std::cout<<"Player 1 you use X"<<std::endl;
        std::cout<<"Player 2 you use O"<<std::endl<<std::endl;
        for(int i=0; i<3; ++i) {
            std::cout<<"   ";
            for(int j=0; j<3; ++j) {
               table[i][j]=cell[index];
               if(index!=2&&index!=5&&index!=8){
               std::cout<<table[i][j]<<" | ";
               } else {
                    std::cout<<table[i][j];
               }
               ++index;
            }
            std::cout<<std::endl;
            if(index<9){
            std::cout<<"  "<<"-----------"<<std::endl;
            }
        }
        std::cout<<std::endl<<std::endl;
    }
    void change(int t) {  // =========  =========  *  *  *   This method helps user to fill field on the game board
        system ("cls");
        Game::cell;
        cell[t-1]='X';
        Game::board();
    }
} ;
int main() {
      // ================================================------------------_________  *  *  *  Client
    WSAData game;
    if((WSAStartup(MAKEWORD(2,2), &game))!=0) {
        std::cout<<"Filed to init socket library. Code : "<<WSAGetLastError()<<std::endl;
        system ("pause");
        return 1;
    }
    SOCKET serverSocket = socket(2,1,6);
        if(serverSocket==INVALID_SOCKET) {
            std::cout<<"Fail to create socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 2;
        }
        SOCKADDR_IN serverGame;
        serverGame.sin_family=2;
        serverGame.sin_port=htons(4324);
        serverGame.sin_addr.s_addr=inet_addr("127.0.0.1");
        if(connect(serverSocket, (sockaddr*)&serverGame,sizeof(serverGame))!=0) {
            std::cout<<"Fail to connect socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 3;
        }
        // ===========================-----------------------------------   ********** Try to send data !!!!!!!!!!!
        // ===========================   * * * Turn of player one

        Game tic_tac_toe;
        tic_tac_toe.board();

            char msg[2]="n";
            char field[1];  // ``````````````````````````````````````This variable exists to change field on the board
            if(serverSocket==INVALID_SOCKET) {std::cout<<"Problem is here"<<std::endl; system ("pause");}
            while(serverSocket!=INVALID_SOCKET){
            std::cout<<"Chose field (enter number of field) : ";
            start:
               std::cin.getline(field, 3);
               msg[0]=field[0];    std::cout<<atoi(&field[0])<<"    "<<msg[0]<<std::endl;
               send(serverSocket, msg, 2, 0);
               recv(serverSocket, msg, 2, 0);

                        if(msg[0]=='N') {
                            std::cout<<"Error (!). Invalid input (!). Chose field again : ";
                            goto start;
                        } else if(msg[0]=='Y') {

                            system ("cls");
                            tic_tac_toe.change(atoi(&field[0]));
                        }
                        closesocket(serverSocket);
                        WSACleanup();
         }

}

Es mi segundo cliente

# include <iostream>
# include <WinSock2.h>
# pragma comment(lib,"ws2_32.lib")
class Game {
    char cell[9];
public:
    Game() {cell[0]='1'; for(int i=0; i<9; ++i){cell[i]=cell[0]+i;}}
    void board() {  // ==================== =======================   * * * This method just prints start game board
        char table[3][3];
        int index=0;
        std::cout<<"   GAME BOARD"<<std::endl<<std::endl;
        std::cout<<"Player 1 you use X"<<std::endl;
        std::cout<<"Player 2 you use O"<<std::endl<<std::endl;
        for(int i=0; i<3; ++i) {
            std::cout<<"   ";
            for(int j=0; j<3; ++j) {
               table[i][j]=cell[index];
               if(index!=2&&index!=5&&index!=8){
               std::cout<<table[i][j]<<" | ";
               } else {
                    std::cout<<table[i][j];
               }
               ++index;
            }
            std::cout<<std::endl;
            if(index<9){
            std::cout<<"  "<<"-----------"<<std::endl;
            }
        }
        std::cout<<std::endl<<std::endl;
    }
    void change(int t) {  // =========  =========  *  *  *   This method helps user to fill field on the game board
        system ("cls");
        Game::cell;
        cell[t-1]='O';
        Game::board();
    }
} ;
int main() {
      // ================================================------------------_________  *  *  *  Client
    WSAData game;
    if((WSAStartup(MAKEWORD(2,2), &game))!=0) {
        std::cout<<"Filed to init socket library. Code : "<<WSAGetLastError()<<std::endl;
        system ("pause");
        return 1;
    }
    SOCKET serverSocket = socket(2,1,6);
        if(serverSocket==INVALID_SOCKET) {
            std::cout<<"Fail to create socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 2;
        }
        SOCKADDR_IN serverGame;
        serverGame.sin_family=2;
        serverGame.sin_port=htons(4324);
        serverGame.sin_addr.s_addr=inet_addr("127.0.0.1");
        if(connect(serverSocket, (sockaddr*)&serverGame,sizeof(serverGame))!=0) {
            std::cout<<"Fail to connect socket. Code : "<<WSAGetLastError()<<std::endl;
            system ("pause");
            return 3;
        }
        // ===========================-----------------------------------   ********** Try to send data !!!!!!!!!!!
        // ===========================   * * * Turn of player one

        Game tic_tac_toe;
        tic_tac_toe.board();

            char msg[2]="n";
            char field[2];  // ``````````````````````````````````````This variable exists to change field on the board
            if(serverSocket==INVALID_SOCKET) {std::cout<<"Problem is here"<<std::endl;}
            while(serverSocket!=INVALID_SOCKET){
            std::cout<<"Chose field (enter number of field) : ";
            while(msg[0]!='Y'){
               std::cin.getline(field, 2);
               msg[0]=field[0]; std::cout<<msg[0]; std::cin.get();
               send(serverSocket, msg, 2, 0);
               recv(serverSocket, msg, 2, 0);
                        if(msg[0]=='N') {
                            std::cout<<"Error (!). Invalid input (!). Chose field again : ";
                        } else if(msg[0]=='Y') {

                            system ("cls");
                            tic_tac_toe.change(atoi(&field[0]));
                        }
            }
         }
}
0
Oleksa 9 oct. 2019 a las 20:14

1 respuesta

La mejor respuesta

Encontré mi problema. No entendí cómo funciona esta conexión.

0
Oleksa 14 oct. 2019 a las 16:09