I've been battling this code all day now, and I'm close to pulling what remains of my hair.
I've got a Server and Client class, and the original goal was for the Server class to have a list of 'Clients' with which it could interact. The entire host of issues aside, I've got some basics working. The Server does register new connections, and I can even send strings from the Client.
Here's the deal though, when I try to send a string with spaces, the whole thing breaks down.
Here's my Send function
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;
}
On the server side of things:
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;
}
}
}
Here's the weird part:
In my Client's main function, when I predefine a string, like "Hello World" the Server prints it out just fine. But when I try to parse user input with std::cin, the message breaks down after the first blank space.
Client Main Function:
#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;
}
And the Output on the Server:
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
If I uncomment the input, and type in "Hello" in the prompt, I get the following output:
In the Constructor Error code: 0Bind code: 0
Error: 0
Connection occured 127.0.0.0
6 Bytes With the message: hello
Error: 0
But if I type "Hello World!" I only get:
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;
reads up to the first whitespace. If you want to read a full line up to the line-end character, make it
std::getline(cin, msg);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.