簡體   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