我整天都在与这段代码作斗争,而且我几乎要拔掉剩下的头发。
我有一个Server and Client类,最初的目标是让Server类具有一个可以与之交互的'Client'列表。除了整个问题之外,我还掌握了一些基础知识。服务器确实注册了新的连接,我什至可以从客户端发送字符串。
不过,这是笔交易,当我尝试发送带空格的字符串时,整个事情崩溃了。
这是我的发送功能
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);