winsock 打印太多

winsock printing too much

我想尝试 server/client 连接之类的东西,所以我修改了 YouTube 教程(C++ 新手)中的代码。到目前为止一切正常,除了当我尝试打印客户端发送的消息时。

用于发送和接收数据的代码如下:

char buf[4096];

while (true)
{
    ZeroMemory(buf, 4096);

    int bytesReceived = recv(clientSocket, buf, 4096, 0);
    if (bytesReceived == SOCKET_ERROR)
    {
        cerr << "Error in recv()! Quitting" << endl;
        break;
    }

    if (bytesReceived == 0)
    {
        cout << "Client disconnected!" << endl;
        break;
    }

    cout << buf << endl;
    send(clientSocket, buf, bytesReceived + 1, 0);
}

发回它工作正常,以及将它打印到控制台。但是,在控制台中,它会在初始输出后打印大量新行。我猜这与buf的大小有关,它是4096,但我不知道如何解决它。

recv() 告诉您实际放入 buf 的字节数,但您在打印 buf 的内容时忽略了该值。您正在使用的 operator<< 需要一个 null-terminated 字符串,但是 recv() 不能保证您的 buf 是 null-terminated (即使客户端发送了一个空终止符,它recv() 退出时可能还没有到达。

打印 bufstd::cout 时使用 write() 而不是 operator<<,这样您就可以指定 bytesReceived 作为要打印的尺寸。

您还向客户端发送了比实际收到的多 1 个字节。调用 send().

时不应将 +1 添加到 bytesReceived

您还需要考虑到 send() 接受的传输字节数可能少于您要求的字节数,因此需要在循环中调用它,就像 recv().

试试这个:

char buf[4096], *ptr;
int bytesReceived, bytesSent, errCode;

while (true)
{
    bytesReceived = recv(clientSocket, buf, sizeof(buf), 0);
    if (bytesReceived == SOCKET_ERROR)
    {
        errCode = WSAGetLastError();
        cerr << "Error " << errCode << " in recv()! Quitting" << endl;
        break;
    }

    if (bytesReceived == 0)
    {
        cout << "Client disconnected!" << endl;
        break;
    }

    cout.write(buf, bytesReceived);
    //cout << endl;

    ptr = buf;
    while (bytesReceived > 0)
    {
        bytesSent = send(clientSocket, ptr, bytesReceived, 0);
        if (bytesSent == SOCKET_ERROR)
        {
            errCode = WSAGetLastError();
            cerr << "Error " << errCode << " in send()! Quitting" << endl;
            break;
        }
        ptr += byteSent;
        bytesReceived -= byteSent;
   }

   if (bytesReceived > 0)
       break;
}