我不是 boost 专家,我正在尝试使用 boost::asio。一切都很好,直到我做的事情搞砸了。不幸的是,我不确定我做了什么... =P
这是发生的事情:
我有一个服务器,它是一个 C++ Builder 应用程序,它打开我的客户端应用程序(Visual Studio C++ DLL)连接的套接字。
当我尝试向套接字写入内容时,我没有收到任何错误,但服务器会收到这样的字符串:“\0SomeText”。我不知道 \0 是从哪里来的。
下面的一些代码可能会解决问题:
void CometClient::SendCommand()
{
if (socket_.is_open())
{
TCommands::iterator it = pending_commands.begin();
while (it != pending_commands.end())
{
std::vector<char> vctCommand;
vctCommand.assign((*it).begin(), (*it).end());
vctCommand.push_back('\n');
boost::shared_ptr<std::vector<char> > ptr_command = boost::make_shared<std::vector<char> > (vctCommand);
boost::asio::async_write(socket_, boost::asio::buffer( *ptr_command ) ,
boost::bind(&CometClient::handle_write_request, this,
boost::asio::placeholders::error, ptr_command )
);
it = pending_commands.erase(it);
}
}
else
{
// Something
}
}
void CometClient::handle_write_request(const boost::system::error_code& err, boost::shared_ptr< std::vector<char> > command)
{
if (!err)
{
std::vector<char> * ptr = command.get();
boost::asio::async_read_until(socket_, response_, "\n",
boost::bind(&CometClient::handle_read_content, this,
boost::asio::placeholders::error));
}
else
{
// Something
}
}
任何帮助将不胜感激。
提前致谢!
编辑:
这是我在 janm 回答后得到的:
void CometClient::SendCommand()
{
// bConnected tells me if the server has already answered me and Connected just tells me if the socket is open (will change in the near future)
if (Connected() && pending_commands.size() && bConnected)
{
std::vector<char> vctCommand;
std::string sCommand(pending_commands.front().c_str());
pending_commands.pop_front();
vctCommand.assign(sCommand.begin(), sCommand.end());
vctCommand.push_back('\n');
boost::shared_ptr<std::vector<char> > ptr_command = boost::make_shared<std::vector<char> > (vctCommand);
boost::asio::async_write(socket_, boost::asio::buffer( *ptr_command, sCommand.length() ) ,
boost::bind(&CometClient::handle_write_request, this,
boost::asio::placeholders::error, ptr_command )
);
}
else
{
// Something
}
}
void CometClient::handle_write_request(const boost::system::error_code& err, boost::shared_ptr< std::vector<char> > command)
{
if (!err)
{
std::vector<char> * ptr = command.get();
boost::asio::async_read_until(socket_, response_, "\n",
boost::bind(&CometClient::handle_read_content, this,
boost::asio::placeholders::error));
SendCommand();
}
else
{
// Something
}
}