Winsock2:当我尝试发送带有空格的字符串时,该函数在遇到空格时似乎停止发送
Winsock2: When I try to send a string with spaces, the function appears stop sending when it encounters a space
我现在整天都在与这段代码作斗争,我快要拔掉我剩下的头发了。
我有一个服务器和客户端类,最初的目标是让服务器类有一个可以与之交互的"客户端"列表。撇开所有问题不谈,我有一些基础知识。服务器确实注册了新连接,我甚至可以从客户端发送字符串。
不过,这是交易,当我尝试发送带有空格的字符串时,整个事情都崩溃了。
这是我的发送功能
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);
相关文章:
- "error: no matching function for call to"构造函数错误
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- Winsock2:当我尝试发送带有空格的字符串时,该函数在遇到空格时似乎停止发送
- 可视代码 删除函数括号内的空格
- 用于删除句点和空格的函数
- 如何从 CreateProcessW 函数的 lpApplicationName 中修剪空格?
- Lua C API 自定义打印函数,在字符串中传递空格时不调用
- 在字符串中的字符前添加空格C++插入函数
- C++ s.replace 函数不输出空格
- 函数调用参数列表 (C++) 中的空格
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数
- C++:将带有空格的cin转换为不带getline函数的字符串
- 使用反向函数并从 txt 文件中删除一定数量信息的空格
- 在名称包含 WinDBG 中的空格的重载函数处设置断点
- 在c++中,函数名和括号之间应该有一个空格
- 在c++中实现一个以空格分隔的方式打印参数的函数
- 编译器要求我在默认函数参数的等号前添加空格
- c++中函数调用前的空格
- 创建一个允许输入中空格的读取函数(C++)