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

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

本文关键字:空格 函数 遇到 Winsock2 字符串      更新时间:2023-10-16

我现在整天都在与这段代码作斗争,我快要拔掉我剩下的头发了。

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

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

这是我的发送功能

int Send(std::string message)
{
const char* cstr = message.c_str();
size_t      len = message.length();
//The +1 is for the  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

但是如果我输入"你好世界! 我只得到:

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);