无法在服务器C ++中连接第二个客户端

时间:2019-10-09 17:14:03

标签: server

我在开发中是一个全新的人,所以我知道我的代码可能是绝对不正确的。但是我在连接服务器中的第二个客户端时遇到了问题。我发现接受功能的错误。当我尝试连接第二个客户端时,我的程序停止工作,服务器正在等待来自第二个客户端的数据,但是我无法发送数据。我尝试使用WSAGetLastError(),但它返回0。请帮助我。 这是我的服务器:

# 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;
          }
      }
}

这是我的第一个客户

# 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();
         }

}

这是我的第二位客户

# 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]));
                        }
            }
         }
}

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。我不明白这种连接是如何工作的。