Garbage value in Boost::Array using with Boost::Asio

404 Views Asked by At

Client is writing like this

    std::string line;
    std::cin>>line;      
    boost::asio::write(socket, boost::asio::buffer(line));


Server is Reading like this

void reader(){   
           socket_.async_read_some(boost::asio::buffer(buf),
           boost::bind(&tcp_connection::handle_read,shared_from_this()));     
  }
void handle_read()
    {
          std::cout.write(buf.data(),1024);
          std::cout<<"\n";
    }
  tcp::socket socket_;
  boost::array<char, 1024> buf;


Now when i am writing a line "hello how are you" from client , it is just printing "hello" and then garbage values
here is the output which server is showing:

helloA0�B��B�����a�Pa�!0�B�b����uB�`�#K|BP�b��D4B���Bb�Pa���e��e�����pc�!0�Be���xB�`�#KcBe�:7B�����e��e���  


how can I remove this garbage values and get complete message/line from client

3

There are 3 best solutions below

5
On BEST ANSWER
  1. operator >> uses whitespace as delimiter like scanf(). You should use std::getline().

    std::getline(std::cin, line);
    
  2. Why do you use cout.write()? just use operator <<.

    std::cout << buf.data();
    

    Of course, you should care '\0'-terminate. Probably boost.asio gives the size of received bytes to your handler.

0
On

>> just reads up to the first delimiter, that is a space in your case.

Your other problem is that you don't tell your receiver how long your message is going to be.

0
On

You have three problems:

First of all, you write 1024 bytes from the buffer, no matter how much data you actually read.

Secondly, TCP connections are streaming, which means there is no message boundaries, and that leads to the possibility that a single receive call can get less than what was sent, and you need multiple receives to receive a complete message.

Thirdly, and which is answered by others, the input operator doesn't work as you expect.