为什么是Cin.getline();结束我与套接字的连接? (网络)(套接字编程)

问题描述 投票:0回答:1

在开始之前,我想澄清一下,我正在使用微软的套接字代码作为模板。

https://learn.microsoft.com/en-us/windows/win32/winsock/complete-client-code

我想与服务器对话以通过一组动作玩游戏,但每当我使用 std::cin.getline(); 时while 循环停止并且套接字关闭。我不确定我在这里做错了什么。

这是我的代码片段: 。 。 .

    const char *sendbuf = "NEWG";
    // comment this when testing cin.
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    
    // Receive until the peer closes the connection
    //  we need to communicate to the server 

    printf(" | | | \\    / _  |  _  _  ._ _   _  | | |\n");
    printf(" o o o  \\/\\/ (/_ | (_ (_) | | | (/_ o o o\n");
    char *usrin;
    std::cout << "Welcome to the tictactoe game !!\n";
    int x = 1;
while (true) {
    std::cout <<"test";
    //std::cin.getline(sendbuf, strlen(sendbuf));
    // if(sendbuf == 0){
    //     std::cout << "give me sometthign to work with!";
    // } 
    std::cout << "test";
    // Send user input to the server
    int iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %d\n", iResult);

    // Receive and print data from the server
    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        printf("Bytes received: %d\n", iResult);
        recvbuf[iResult] = '\0'; // Null-terminate the received data
        printf("Received data: %s\n", recvbuf);
    } else if (iResult == 0) {
        printf("Connection closed\n");
    } else {
        printf("recv failed with error: %d\n", WSAGetLastError());
    }
    
}

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}

。 。 .

任何帮助都会非常感谢,我很迷失 .

我尝试将变量类型从“const char *”更改为简单的“char”,然后更改为“char *”。 它给了我一个错误..

我尝试使用“>>”而不是 getline()。 同样的事情发生了

我尝试从终端中初始化的outehr变量中获取另一个值。 这不起作用,因为问题来自函数“cin”。

c++ sockets networking winsock
1个回答
0
投票

在您注释的代码中,您将

std::cin.getline()
读入
sendbuf
,这是一个指向
字符串文字
const char*指针,即指向只读内存。因此,您的代码会调用未定义的行为,这可能会导致访问冲突,从而杀死您的代码。

您需要将

getline()
读入 可写 内存,例如您的
recvbuf
数组。

© www.soinside.com 2019 - 2024. All rights reserved.