首先,我想声明我是 C++ 的初学者,并且总体上是 boost,尽管我确实有一些使用 Java 和 C# 等语言的经验。
话虽如此,我在通过 Boost TCP 套接字传输数据时遇到了问题。我正在使用这段代码:
发送:
tcp::socket s(io_service);
boost::asio::connect(s, iterator);
string response = static_cast<ostringstream*>( &(ostringstream() << arg1) )->str()
+ "," + static_cast<ostringstream*>( &(ostringstream() << arg2) )->str()
+ "," + static_cast<ostringstream*>( &(ostringstream() << arg3) )->str()
+ "," + static_cast<ostringstream*>( &(ostringstream() << arg4) )->str()
+ "," + static_cast<ostringstream*>( &(ostringstream() << arg5) )->str()
+ "," + static_cast<ostringstream*>( &(ostringstream() << arg6) )->str();
//pad the rest
while (response.length() < max_length)
{
response += ' ';
}
boost::asio::write(s, boost::asio::buffer(response, sizeof(response)));
读书:
tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
while(true)
{
socket_ptr sock(new tcp::socket(io_service));
a.accept(*sock);
boost::thread t(boost::bind(session, sock));
}
...
void session(socket_ptr sock)
{
char data[max_length];
size_t length;
try
{
while(true)
{
boost::system::error_code error;
//size_t length = sock->read_some(boost::asio::buffer(data), error);
length = boost::asio::read(*sock, boost::asio::buffer(data, sizeof data));
std::cout << "Length " << length << endl;
if (error == boost::asio::error::eof)
{
break; // Connection closed cleanly by peer.
}
else if (error)
{
throw boost::system::system_error(error); // Some other error.
}
}
}
catch (std::exception& e)
{
std::cout << data << endl;
string message = e.what();
if(std::string::npos != message.find(END_OF_FILE))
{
domeSomethingWithTheData(data);
memset(data, 0, sizeof data);
}
else
{
std::cout << data <<endl;
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
}
我无法理解的是,无论我使用什么(boost::asio::read
或sock->read_some
),我都不会得到超过 32 个字符的数据。我尝试将缓冲区的大小增加到2048
,但问题仍然存在。
缓冲区总是包含超过 32 个字符(其中大部分是垃圾),但我假设这些字符实际上并不是从客户端发送的,而是来自服务器端缓冲区的实际分配,因为std::cout << "Length " << length
打印出 32。
任何有关我如何从客户端向服务器发送任意数量的字符的信息都将不胜感激。
编辑:
在 Rafal Rawicki 提供的指针之后,我现在正在使用以下代码:
boost::asio::streambuf buffer;
boost::asio::read_until(*sock, buffer, '\n');
std::istream is(&buffer);
std::string line;
std::getline(is, line);
std::cout << line << std::endl;
客户端保持不变,唯一的例外是我\n
在最后添加了一个。然而,这会产生很多End of file
异常。