disaste0_0 2024-01-20 12:30 采纳率: 81.6%
浏览 13
已结题

c++服务器和客户端通信

整体的代码写完了但是运行起来有问题当客户端发送完第一次信息服务器就直接断连了
题目要
1使客户端可以继续发送信息直到在信息中发送 "quit "。同时服务器应显示收到的每条信息。收到 "quit "信息后,客户端和服务器应用程序都应退出。

2服务器向客户端发送字符串 "Received Message(已收到消息)",确认已收到用户定义的消息。客户端应在自己的屏幕上输出收到的信息,然后准备发送更多信息,直到发送 "quit "信息。发送 "quit "信息后,客户端和服务器应用程序都应退出。
3用名为 "bye "的新命令更新代码。当用户在客户端输入 "bye "时,服务器应作出响应,客户端应终止,让服务器等待新的连接。

这是server的代码

#include <windows.networking.sockets.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")

using namespace std;

int main()
{
    //starts Winsock DLLs        
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
        return 0;

    //create server socket
    SOCKET ServerSocket;
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET) {
        WSACleanup();
        return 0;
    }

    //binds socket to address
    sockaddr_in SvrAddr;
    SvrAddr.sin_family = AF_INET;
    SvrAddr.sin_addr.s_addr = INADDR_ANY;
    SvrAddr.sin_port = htons(27000);
    if (bind(ServerSocket, (struct sockaddr*)&SvrAddr, sizeof(SvrAddr)) == SOCKET_ERROR)
    {
        closesocket(ServerSocket);
        WSACleanup();
        return 0;
    }

    //listen on a socket
    if (listen(ServerSocket, 1) == SOCKET_ERROR) {
        closesocket(ServerSocket);
        WSACleanup();
        return 0;
    }


    cout << "Waiting for client connection\n" << endl;

    loophead:

    //accepts a connection from a client
    SOCKET ConnectionSocket;
    ConnectionSocket = SOCKET_ERROR;
    if ((ConnectionSocket = accept(ServerSocket, NULL, NULL)) == SOCKET_ERROR) {
        closesocket(ServerSocket);
        WSACleanup();
        return 0;
    }

    cout << "Connection Established" << endl;
    while(1){
        //receives RxBuffer
        char RxBuffer[128] = {};
        recv(ConnectionSocket, RxBuffer, sizeof(RxBuffer), 0);
        if (sizeof(RxBuffer) > 0) {
            cout << "Msg Rx: " << RxBuffer << endl;

            while (1) {
                // if the server got message bye then will disconnect to the client and wait for the new connect
                if (RxBuffer == "bye") {
                    closesocket(ConnectionSocket);
                    cout << "Server wait for next connect";
                    goto loophead;
                }

                // if server got quit, the both side will close
                else if (RxBuffer == "quit") {
                    closesocket(ConnectionSocket);
                    closesocket(ServerSocket);
                    cout << "Is close";
                    break;
                }

                // if didn't get any quit or bye, the server can keep receive the message from client
                else {
                    
                    cout << "send Received Message" << endl;
                    send(ConnectionSocket, "Received Message", sizeof("Received Message"), 0);
                    break;
                }

            }
        }
        else {
            goto loophead;
        }

    }

    closesocket(ConnectionSocket);    //closes incoming socket
    closesocket(ServerSocket);        //closes server socket    
    WSACleanup();                    //frees Winsock resources

    return 1;
}

这是clien 的代码

#include <windows.networking.sockets.h>
#pragma comment(lib, "Ws2_32.lib")

#include <iostream>
using namespace std;

int main()
{
    //starts Winsock DLLs
    WSADATA wsaData;
    if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) {
        return 0;
    }

    //initializes socket. SOCK_STREAM: TCP
    SOCKET ClientSocket;
    ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ClientSocket == INVALID_SOCKET) {
        WSACleanup();
        return 0;
    }

    //Connect socket to specified server
    sockaddr_in SvrAddr;
    SvrAddr.sin_family = AF_INET;                        //Address family type itnernet
    SvrAddr.sin_port = htons(27000);                    //port (host to network conversion)
    SvrAddr.sin_addr.s_addr = inet_addr("127.0.0.1");    //IP address
    if ((connect(ClientSocket, (struct sockaddr*)&SvrAddr, sizeof(SvrAddr))) == SOCKET_ERROR) {
        closesocket(ClientSocket);
        WSACleanup();
        return 0;
    }

    char TxBuffer[128] = {};
    char RxBuffer[128] = {};
    
    while (1) {
        
        memset(TxBuffer, 0, 128);
        memset(RxBuffer, 0, 128);
        cout << "Enter a String to transmit" << endl;
        cin >> TxBuffer;
        send(ClientSocket, TxBuffer, sizeof(TxBuffer), 0);
        // if the client send the message quit then will disconnect
        if (TxBuffer == "quit") {
            closesocket(ClientSocket);
            break;
        }
        // if the client send the message bye then will disconnect
        else if (TxBuffer == "bye") {
            closesocket(ClientSocket);
            break;
        }
        recv(ClientSocket, RxBuffer, sizeof(RxBuffer), 0);
        cout << "clint res: " << RxBuffer << endl;
        
    }
    //closes connection and socket
    closesocket(ClientSocket);

    //frees Winsock DLL resources
    WSACleanup();

    return 1;
}

ai的回答就算了

  • 写回答

10条回答 默认 最新

  • micthis 2024-01-20 15:35
    关注

    好了:

    img

    img

    server:

    //#include <Winsock2.h>
    //#include <windows.h>
    #include <windows.networking.sockets.h>
    #include <iostream>
    #include <cstring>
    
    #pragma comment(lib, "Ws2_32.lib")
    
    using namespace std;
    
    int main()
    {
        //starts Winsock DLLs        
        WSADATA wsaData;
        if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
            return 0;
        //create server socket
        SOCKET ServerSocket;
        ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (ServerSocket == INVALID_SOCKET) {
            WSACleanup();
            return 0;
        }
        //binds socket to address
        sockaddr_in SvrAddr;
        SvrAddr.sin_family = AF_INET;
        SvrAddr.sin_addr.s_addr = INADDR_ANY;
        SvrAddr.sin_port = htons(27000);
        if (bind(ServerSocket, (struct sockaddr*)&SvrAddr, sizeof(SvrAddr)) == SOCKET_ERROR)
        {
            closesocket(ServerSocket);
            WSACleanup();
            return 0;
        }
        //listen on a socket
        if (listen(ServerSocket, 1) == SOCKET_ERROR) {
            closesocket(ServerSocket);
            WSACleanup();
            return 0;
        }
        cout << "Waiting for client connection\n" << endl;
        bool quit=false;
        //accepts a connection from a client
        SOCKET ConnectionSocket;
        ConnectionSocket = SOCKET_ERROR;
        while(!quit) {
            if ((ConnectionSocket = accept(ServerSocket, NULL, NULL)) == SOCKET_ERROR) {
                closesocket(ServerSocket);
                WSACleanup();
                return 0;
            }
            cout << "Connection Established" << endl;
            while(true) {
                //receives RxBuffer
                char RxBuffer[128] = {};
                int r=recv(ConnectionSocket, RxBuffer, sizeof(RxBuffer), 0);
                if(r!=SOCKET_ERROR && r>0) {
                    cout << "Msg Rx: " << RxBuffer << endl;
                    // if the server got message bye then will disconnect to the client and wait for the new connect
                    if(strcmp(RxBuffer,"bye")==0) {
                        closesocket(ConnectionSocket);
                        cout << "Server wait for next connect" << endl;
                        break;
                    }
                    // if server got quit, the both side will close
                    else if (strcmp(RxBuffer,"quit")==0) {
                        closesocket(ConnectionSocket);
                        closesocket(ServerSocket);
                        cout << "Is close";
                        quit=true;
                        break;
                    }
                    // if didn't get any quit or bye, the server can keep receive the message from client
                    else {
                        cout << "send Received Message" << endl;
                        send(ConnectionSocket, RxBuffer, strlen(RxBuffer), 0);
                    }
                } else {
                    break;
                }
            }
        }
        closesocket(ConnectionSocket);    //closes incoming socket
        closesocket(ServerSocket);        //closes server socket    
        WSACleanup();                    //frees Winsock resources
        return 1;
    }
    

    client:

    //#include <Winsock2.h>
    //#include <windows.h>
    #include <windows.networking.sockets.h>
    #include <iostream>
    #include <cstring>
    
    #pragma comment(lib, "Ws2_32.lib")
    
    using namespace std;
    
    int main()
    {
        //starts Winsock DLLs
        WSADATA wsaData;
        if ((WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0) {
            return 0;
        }
        //initializes socket. SOCK_STREAM: TCP
        SOCKET ClientSocket;
        ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (ClientSocket == INVALID_SOCKET) {
            WSACleanup();
            return 0;
        }
        //Connect socket to specified server
        sockaddr_in SvrAddr;
        SvrAddr.sin_family = AF_INET;                        //Address family type itnernet
        SvrAddr.sin_port = htons(27000);                    //port (host to network conversion)
        SvrAddr.sin_addr.s_addr = inet_addr("127.0.0.1");    //IP address
        if ((connect(ClientSocket, (struct sockaddr*)&SvrAddr, sizeof(SvrAddr))) == SOCKET_ERROR) {
            closesocket(ClientSocket);
            WSACleanup();
            return 0;
        }
        char TxBuffer[128] = {};
        char RxBuffer[128] = {};
        while (1) {
            memset(TxBuffer, 0, 128);
            memset(RxBuffer, 0, 128);
            cout << "Enter a String to transmit" << endl;
            cin.getline(TxBuffer,sizeof(TxBuffer));
            send(ClientSocket, TxBuffer, strlen(TxBuffer), 0);
            // if the client send the message quit then will disconnect
            if (strcmp(TxBuffer,"quit")==0) {
                closesocket(ClientSocket);
                break;
            }
            // if the client send the message bye then will disconnect
            else if (strcmp(TxBuffer,"bye")==0) {
                closesocket(ClientSocket);
                break;
            }
            recv(ClientSocket, RxBuffer, sizeof(RxBuffer), 0);
            cout << "clint res: " << RxBuffer << endl;
        }
        //closes connection and socket
        closesocket(ClientSocket);
        //frees Winsock DLL resources
        WSACleanup();
        return 1;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(9条)

报告相同问题?

问题事件

  • 系统已结题 1月28日
  • 已采纳回答 1月20日
  • 修改了问题 1月20日
  • 创建了问题 1月20日

悬赏问题

  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办
  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了