我正在学习C ++和套接字,但遇到了一个问题,我创建了一个小示例应用程序来模拟它。创建一个侦听套接字,然后连接到该套接字,并将客户端套接字存储在类型为SOCKET *的向量中。

在第三个客户端套接字连接之后,我然后遍历该向量并将其关闭。前一个成功,但最后一个2失败,错误为-1,就好像套接字已关闭一样。但实际上只有1个插槽关闭。

下面是代码

WindowsSocket socketManager(&bitsLibrary);
    socketManager.createSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, 500, 1024, "127.0.0.1");

    socketManager.bindAndStartListening();
    vector<SOCKET *> clientSocketList;
    int i = 0;
    while (i < 3)
    {
        sockaddr_in client;
        SOCKET clientSock = socketManager.acceptClientAndReturnSocket(&client);

        cout << "Client Port: " << ntohs(client.sin_port) << endl;

        //Add the client socket to the vector
        clientSocketList.push_back(&clientSock);
        i++;

        string data = socketManager.receiveDataOnSocket(&clientSock);

        socketManager.sendToSocket(&clientSock, "Hello, here is a response");
    }

    int index = 1;
    for (std::vector<SOCKET *>::iterator it = clientSocketList.begin(); it != clientSocketList.end(); ++it)
    {
        cout << "Closing socket " << index << " of " << clientSocketList.size() << endl;
        try
        {
            SOCKET *socket = (SOCKET *)*it;
            socketManager.closeSocket(socket);
        }
        catch (SocketException ex)
        {
            cout << "Failed to close client socket. Error: " << ex.what() << endl;
        }
        index++;
    }

    //socketManager.closeSocket(socketManager.returnSocket());
    //socketManager.closeSocket(&clientSock);

    return EXIT_SUCCESS;


创建套接字函数如下:

bool WindowsSocket::createSocket(int family, int socketType, int protocol, int port, int bufferLength, string ipAddress)
{
    stringstream logstream;
    //Call the base method to do the prep work e.g. create the buffer
    BaseSocket::createsocket(port, bufferLength);

    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0)
    {
        logstream << "WSAStartup failed with error: " << iResult;
        this->bitsLibrary->writeToLog(logstream.str(), "WindowsSocket", "createSocket");
        logstream.clear();
        logstream.str(string());
        return false;
    }
    this->serverSocket = socket(family, socketType, protocol);
    this->serv_addr.sin_family = family;
    if (ipAddress.empty())
    {
        this->serv_addr.sin_addr.s_addr = INADDR_ANY;
    }
    else
    {
        this->serv_addr.sin_addr.s_addr = inet_addr(ipAddress.c_str());
    }
    this->serv_addr.sin_port = htons(port);

    return true;
}


bindAndStartListening函数如下:

bool WindowsSocket::bindAndStartListening(int backlog)
{
    stringstream logstream;

    //iResult = ::bind(this->serverSocket, result->ai_addr, (int)result->ai_addrlen);
    iResult = ::bind(this->serverSocket, (SOCKADDR *)&this->serv_addr, sizeof(this->serv_addr));
    if (iResult != 0)
    {
        logstream << "Socket binding failed with error: " << iResult;
        this->bitsLibrary->writeToLog(logstream.str(), "WindowsSocket", "bindAndStartListening");
        logstream.clear();
        logstream.str(string());
        FreeAddrInfo(result);
        closesocket(this->serverSocket);
        WSACleanup();
        return false;
    }

    freeaddrinfo(result);
    iResult = listen(this->serverSocket, backlog);
    if (iResult == SOCKET_ERROR)
    {
        throw SocketException(this->getErrorStringFromErrorCode(WSAGetLastError()).c_str());
        return false;
    }
    logstream << "Socket has binded and is now listening";
    this->bitsLibrary->writeToLog(logstream.str(), "WindowsSocket", "bindAndStartListening");
    return true;
}


acceptClientAndReturnSocket函数如下:

SOCKET WindowsSocket::acceptClientAndReturnSocket(sockaddr_in *clientAddr)
{
    SOCKET clientSocket = INVALID_SOCKET;
    //sockaddr_in clientAddr;
    socklen_t sin_size = sizeof(struct sockaddr_in);
    clientSocket = accept(this->serverSocket, (struct sockaddr*)clientAddr, &sin_size);
    return clientSocket;
}


当我调试``clientSocketList`包含的每一项时,似乎包含与下面的屏幕快照所示相同的值:

c&#43;&#43; - 将套接字存储在 vector 中然后关闭,同一套接字不断增加-LMLPHP

我不明白为什么将相同的客户端套接字添加到向量中。

最佳答案

while(i < 3)循环的每次迭代都会创建一个新的SOCKET。您保存它的地址,但是在迭代结束时将其销毁。您要保存的是对象在堆栈上的地址,并且每次迭代时最新的clientSock都位于同一地址。

clientSocketListstd::vector<SOCKET*>,而您可能想使用std::vector<SOCKET>

08-26 20:14
查看更多