Winsock收到的字节数无效

时间:2015-04-26 11:11:20

标签: c++ c++11 winsock

我在尝试验证接收的字节数时,目前正遇到Winsock相关问题。

在我的应用程序中,我使用非阻塞套接字来抛出自己的Timeout异常。这里是Winsock初始化的相应代码:

// Initialize Winsock
WSAData winSockData;
WORD dllVersion = MAKEWORD(2, 1);
long iResult = WSAStartup(dllVersion, &winSockData);
if (iResult != NO_ERROR)
    return;

addrinfo* serverAddress = nullptr;
addrinfo* ptr = nullptr, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

iResult = getaddrinfo("127.0.0.1", "10011", &hints, &serverAddress);
if (iResult != 0)
    return;

// Create communication socket
SOCKET connectSocket = socket(AF_INET, SOCK_STREAM, /*IPPROTO_TCP*/0);
if (connectSocket == INVALID_SOCKET)
    return;

// Establish connection to server
iResult = connect(connectSocket, serverAddress->ai_addr, (int)serverAddress->ai_addrlen);
if (iResult == SOCKET_ERROR)
    return;

// Set socket to non-blocking
ULONG mode = 1;
m_iResult = ioctlsocket(m_connectSocket, FIONBIO, &mode);
if (m_iResult == SOCKET_ERROR)
    return;

// server address info not needed anymore
freeaddrinfo(serverAddress);

应用程序首先连接到给定的telnet服务器,发送请求然后等待相应的响应消息。

传入的数据存储在一个名为m_serverMsg的适当字符数组中(固定大小为BUFSIZE,当前设置为4200字节)。

如果检索服务器响应消息的时间很长(g_requestTimeout中存储的最大允许时间),则会抛出我自己的TimeoutException

如果在消息缓冲区中找到换行符(\r\n),则服务器消息已到达终点。

但是,检索服务器响应消息的以下部分未按预期工作。预期的传入数据字节为1,040,但实际字节始终为3,435,973,836

unsigned long long startTime = getWallTimeInMs();
bool retry = true;
unsigned int receivedBytes = 0;
// Fetch server response
do
{

    try
    {

        m_iResult = fetchMessage(m_connectSocket, m_serverMsg, int(BUFSIZE - receivedBytes));
        if (m_iResult == SOCKET_ERROR)
            throw std::exception();

        if (m_iResult > 0)
        {
            for (unsigned int i = receivedBytes; i < receivedBytes + m_iResult; i++)
            {
                char* eol = strstr(m_serverMsg, "\r\n");
                if (eol)
                {
                    retry = false;
                    break;
                }
            }

            receivedBytes += m_iResult;
        }
    }
    catch (CommException e)
    {
        // in case there's a short delay in retrieving the server response message
        if (getWallTimeInMs() - startTime < g_requestTimeout)
            Sleep(20);
        else
            // response timeout exceeded; connection has been lost
            throw CommException("server not responding in time.", CommProblem::ConnectionLost);
    }
    catch (std::exception& e)
    {
        std::cout << "There was a socket related problem." << std::endl;
        std::cout << "Error code: " << WSAGetLastError() << std::endl;
    }

} while (retry);

这就是函数fetchMessage()的样子:

int CommCenter::fetchMessage(SOCKET socket, char* buffer, int bufSize, int flags)
{
    int result = recv(socket, buffer, bufSize, flags);
    // if operation couldn't be executed (e.g. because server is down),
    // throw according exception
    if (result == SOCKET_ERROR)
    {
        if (WSAGetLastError() == WSAEWOULDBLOCK)
            throw CommException("delay in connection.", CommProblem::Delay);
        else throw;
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

这部分

<Button Background="{Binding Background, ElementName=myBindingTarget}" />
<!-- or some other binding -->
<Button Background="{Binding }"/>

不正确,for (unsigned int i = receivedBytes; i < receivedBytes + m_iResult; i++) { if (m_serverMsg[i] == '\r\n') { retry = false; break; } } '\r\n'不同,因此您无法像这样比较它。

要更正它,请使用strstr这样的功能

"\r\n"

或将char* eol = strstr(m_serverMsg, "\r\n"); if(eol != NULL) { retry = false; break; } 转换为m_serverMsg并使用std::string方法

find