Winsock发送两次c ++消息

时间:2018-06-18 00:05:18

标签: c++ sockets network-programming winsock2

所以我的问题是,当我在do-while循环中使用WinSock“send”时,PUTTY会收到它两次。

char sendBuffer[] = "this is my message to the world";
do
{
    iResult = recv(clientSocket, recvBuffer, DEFAULTBUFFERLEN, 0);
    if(iResult > 0)
    {
        std::cout << "Received bytes: " << iResult << std::endl;

        std::cout << recvBuffer << std::endl;
        //Successful receive, now send back a message
        Message("Now it's your turn to say something!");
        //std::cin.getline(sendBuffer, DEFAULTBUFFERLEN);
        std::cin.get();
        iSendResult = send(clientSocket, sendBuffer, sizeof(sendBuffer), 0);
        if(iSendResult == SOCKET_ERROR)
        {
            Message("Error with send. ERROR: " + WSAGetLastError());
            closesocket(clientSocket);
            WSACleanup();
            return 8;
        }

        std::cout << "Bytes sent: " << iSendResult << std::endl;
    }
    else if(iResult == 0)
    {//Nothing has been received, client has disconnected
        Message("Closing connection with client");
    }else
    {// there was an errror and the connection needs to be closed
        Message("Error Receiving. Error: " + WSAGetLastError());
        closesocket(clientSocket);
        WSACleanup();
        return 9;
    }

}while(iResult > 0);

代码工作方式不然,编译和整体,顺利,唯一的问题是发送调用由于某种原因发送它两次。

我在此之前调用一次发送只是说“欢迎使用服务器”但实际上只发送一次。它只是这个位中的一个发送两次。 我正在使用mingw进行编译,这是我的构建脚本

g++ server.cpp -o server -lws2_32 -lwsock32

编辑:根据我的调试器,代码在从客户端收到初始消息时运行一次但是再次运行并在再次运行时收到“\ r \ n”,因此重复的消息无需等待新的客户留言

1 个答案:

答案 0 :(得分:0)

因此,在进行一些调试后,我发现了问题所在,当您按Enter键(或类似的操作)时,腻子会发送一条额外的消息。因此,解决方案是使用满足以下条件的if语句包装处理收到消息的代码: / p>

if((std::string)recvBuffer != "\r\n" || (std::string)recvBuffer != "\n")