客户端和服务器无法交换数据,因为都得到 "stuck"

Client and server can not exchange data because both get "stuck"

简介:

我研究了 blocking TCP server and blocking TCP client 的 MSDN 示例。

鉴于修改这些示例以创建简单的聊天应用程序,我想尝试一些简单的东西。

首先,我尝试实现以下内容:

相关信息

对于冗长的代码,我提前表示歉意,但我坚信为客户端和服务器提交 SSCCE 对我来说是相关的,以便社区有机会解决问题。

我已尝试使代码尽可能少,但不想省略基本的错误检查。

您可以 copy/paste 都在单个 .cpp 文件中,它们应该编译并且 运行 没有问题:

服务器代码:

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>

#pragma comment (lib, "Ws2_32.lib")

#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(void) 
{
    WSADATA wsaData;
    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iResult;
    char recvbuf[DEFAULT_BUFLEN] = "";
    int recvbuflen = DEFAULT_BUFLEN;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket, 
    // because I want to accept only 1 client
    closesocket(ListenSocket);

    // ===================== let us try to send a message...
    std::string message = "Test message from server !!!";
    int total = message.size();
    const int messageLength = message.size();

    while (iResult = send( ClientSocket,
        // send only the missing part of the string, if send failed to deliver entire packet:
        // we move the start of the string forward by messageLength - total
        // while we send remaining number of bytes, which is held in total
        message.substr(messageLength - total, total).c_str(), total, 0),
        iResult > 0)
    {
        total -= iResult;
    }

    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

/*  // adding this, seems to solve the problem ???
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }
*/
    // receive response from client...
    while (iResult = recv(ClientSocket, recvbuf, recvbuflen, 0), iResult > 0)
    {
        printf("%s", recvbuf);
        memset(recvbuf, '[=11=]', sizeof(recvbuf));
    }

    if(iResult < 0)
    {
        printf("recv failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

    getchar();  // so I can stop the console from immediately closing...
    return 0;
}

客户代码:

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>

#pragma comment (lib, "Ws2_32.lib")


#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"

int __cdecl main(int argc, char **argv) 
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;

    char recvbuf[DEFAULT_BUFLEN] = "";
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) 
    {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    // Resolve the server address and port
    iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) 
    {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) 
    {
        // Create a SOCKET for connecting to server
        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        if (ConnectSocket == INVALID_SOCKET) 
        {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        if (iResult == SOCKET_ERROR) 
        {
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) 
    {
        printf("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }

    // receive message from server...
    while (iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0), iResult > 0)
    {
        printf("%s", recvbuf);
        memset(recvbuf, '[=12=]', sizeof(recvbuf));
    }

    if(iResult < 0)
    {
        printf("recv failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // ===================== let us try to send a message...
    std::string message = "Client response...";
    int total = message.size();
    const int messageLength = message.size();

    while (iResult = send( ConnectSocket,
        // send only the missing part of the string, if send failed to deliver entire packet:
        // we move the start of the string forward by messageLength - total
        // while we send remaining number of bytes, which is held in total
        message.substr(messageLength - total, total).c_str(), total, 0),
        iResult > 0)
    {
        total -= iResult;
    }

    if (iResult == SOCKET_ERROR) {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

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

    getchar();  // so I can stop the console from immediately closing...
    return 0;
}

问题:

我已经实施了解决方案,但没有得到预期的结果。

服务器发送消息,客户端成功接收并显示它,但随后客户端无限卡住,而不是将其响应发送给服务器,这也无限阻塞了服务器。

我为解决这个问题所做的努力:

第一次尝试:

使用调试器,我在客户端的接收块之后放置了断点,只是为了确定客户端在收到第一条消息后永远不会到达那里。

我相信 while 循环应该再次调用 recv,这应该 return 0,从而强制循环结束。

在我点击 Continue 之后,调试器甚至没有继续显示客户端接收缓冲区的内容,而是表现出我目前无法描述的行为,因为我不是以英语为母语的人。

第二次尝试:

我也曾尝试使用 CreateThread 将服务器的接收循环放入线程中,但这也无济于事。

我也试过将客户端的接收循环放到线程中,但也失败了。

我曾尝试将客户端和服务器接收循环都放入线程中,但也失败了。

第三次尝试:

最后,我在服务器代码中添加了对shutdown( ClientSocket, SD_SEND)的调用,你会在代码的下方找到它,它被注释掉了。

这似乎解决了问题,但我不确定这是否是正确的解决方案,因为我刚开始使用 Winsock。

问题:

再次,对于冗长的 post,我深表歉意,但作为新手,我已尝试提供尽可能多的信息,以使您的任务更轻松。

在简要浏览了您的代码后,我敢猜测客户端中的以下代码块:

while (iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0), iResult > 0)
{
    printf("%s", recvbuf);
    memset(recvbuf, '[=10=]', sizeof(recvbuf));
}

实际上是你的问题。您提到关闭服务器端的套接字可以解决问题。对于套接字,只要套接字处于活动状态或直到数据通过,recv 调用就会阻塞,但是当套接字关闭时,您将获得 0 的 recv。

如果你只想接收 one 消息,而不是在 recv 上循环,你应该在处理完第一个 recv 后循环回 recv 调用,或者你应该在套接字上轮询先看看有没有实际可用的数据。