我正在调整here中的asio聊天客户端示例,以便与发布基于行的数据的现有客户端应用程序进行通信。这是我的代码:
#include <cstdlib>
#include <deque>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
boost::mutex global_stream_lock;
using boost::asio::ip::tcp;
typedef std::deque<std::string> simple_message_queue;
class chat_client
{
public:
chat_client(boost::asio::io_service& io_service,
tcp::resolver::iterator endpoint_iterator)
: io_service_(io_service),
socket_(io_service)
{
if(DEBUGGING) std::cout << "[" << __FUNCTION__ << "]" << std::endl;
boost::asio::async_connect(socket_, endpoint_iterator,
boost::bind(&chat_client::handle_connect, this,
boost::asio::placeholders::error));
}
void write(const std::string& i_msg)
{
io_service_.post(boost::bind(&chat_client::do_write, this, i_msg));
}
void close()
{
io_service_.post(boost::bind(&chat_client::do_close, this));
}
private:
void handle_connect(const boost::system::error_code& error)
{
if (!error)
{
boost::asio::async_read_until(socket_, simple_msg_buf_, "\n",
boost::bind(&chat_client::handle_read_message, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
}
void handle_read_message(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if (!error && bytes_transferred)
{
// Remove newline from input.
simple_msg_buf_.commit(bytes_transferred);
std::istream is(&simple_msg_buf_);
std::string s;
is >> s;
std::cout << s << std::endl;
boost::asio::async_read_until(socket_, simple_msg_buf_, "\n",
boost::bind(&chat_client::handle_read_message, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else
{
do_close();
}
}
void do_close()
{
socket_.close();
}
private:
boost::asio::io_service& io_service_;
tcp::socket socket_;
boost::asio::streambuf simple_msg_buf_;
simple_message_queue write_simple_msgs;
};
int main(int argc, char* argv[])
{
try
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("127.0.0.1", "20001");
tcp::resolver::iterator iterator = resolver.resolve(query);
chat_client c(io_service, iterator);
boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));
std::string input;
while(std::cin)
{
std::getline(std::cin,input);
// do something with input...
}
c.close();
t.join();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
我与服务器通信没有问题,但我收到的数据格式不是应该的。我想逐行解析数据,所以我在Mac OS X(intel)上使用"\n"
分隔符。例如,假设我希望格式的数据:This:(IS SOME) data;
我通过上面的代码实际收到的格式是:
This:(IS
SOME)
data
因此看起来"\n"
字符的处理方式与空格(" "
)相同。
实际上,如果我用"\n"
替换" "
分隔符,则行为是相同的。
我也尝试了"\r"
和"\r\n"
,但两种模式都没有被选中。
有谁知道可能导致这种情况的原因?