繁体   English   中英

Winsock2:当我尝试发送带有空格的字符串时,该函数出现在遇到空格时停止发送

[英]Winsock2: When I try to send a string with spaces, the function appears stop sending when it encounters a space

我一整天都在与这个代码作斗争,我几乎要拔掉我剩下的头发了。

我有一个 Server 和 Client 类,最初的目标是让 Server 类拥有一个可以与之交互的“客户端”列表。 撇开所有问题不谈,我已经掌握了一些基础知识。 服务器确实注册了新连接,我什至可以从客户端发送字符串。

不过,这就是交易,当我尝试发送一个带空格的字符串时,整个事情都会崩溃。

这是我的发送功能

    int Send(std::string message)
    {
        const char* cstr = message.c_str();
        size_t      len = message.length();

        //The +1 is for the \0 character that c_str() adds
        //this->server is a socket that has already been connected to and accepted by the server
        int bytes = send(this->server, cstr, len + 1, 0);  
        return bytes;
    }

在服务器端:

void Run()
    {
        char buffer[1024];
        while (1)
        {
            listen(server, 0);
            SOCKET incoming_sock;
            int clientAddrSize = sizeof(clientAddr);
            if ((incoming_sock = accept(server, (SOCKADDR*)&clientAddr, &clientAddrSize)) != INVALID_SOCKET)
            {
                std::cout << "Error: " << WSAGetLastError() << std::endl;
                std::cout << "Connection occured " << printIP(clientAddr.sin_addr.s_addr) << std::endl;
                int bytes = recv(incoming_sock, buffer, sizeof(buffer), 0);
                std::cout << bytes << " Bytes With the message: " << buffer << std::endl;
                std::cout << "Error: " << WSAGetLastError() << std::endl;
            }
            else
            {
                std::cout << "Error: " << WSAGetLastError() << std::endl;
            }
        }
    }

这是奇怪的部分:

在我的客户端的主函数中,当我预定义一个字符串时,比如“Hello World”,服务器将它打印出来就好了。 但是当我尝试使用 std::cin 解析用户输入时,消息在第一个空格后中断。

客户端主要功能:

#include "Client.h"
#include <iostream>

int main()
{
    Client c("127.0.0.1", 5555, 1);
    std::string msg = "Hello World!";
    while (msg.compare("exit") != 0)
    {

        //std::cout << "Send: ";
        //std::cin >> msg;
        int bytes = c.Send(msg);
        std::cout << "Sent \"" << msg << "\"" << "Bytes: " << bytes << std::endl;
    }
    while (1);
    return 0;
}

以及服务器上的输出:

In the Constructor Error code: 0Bind code: 0
Error: 0
Connection occured 127.0.0.0
13 Bytes With the message: Hello World!
Error: 0

如果我取消对输入的注释,并在提示中输入“Hello”,我会得到以下输出:

In the Constructor Error code: 0Bind code: 0
Error: 0
Connection occured 127.0.0.0
6 Bytes With the message: hello
Error: 0

但是如果我输入“Hello World!” 我只得到:

In the Constructor Error code: 0Bind code: 0
Error: 0
Connection occured 127.0.0.0
6 Bytes With the message: Hello
Error: 0

std::cin >> msg; 读到第一个空格。 如果您想读取一行到行尾字符的完整行,请将其设为

std::getline(cin, msg);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM