我有一个问题,我在客户端和服务器之间有一个 TCP 连接,当客户端初始化时,他向服务器发送一条消息,并且服务器通过一条欢迎消息来回答。
所有这些在本地网络上都可以正常工作。
所以我的问题是我使用 async_write 和 async_read (因为我需要我的服务器是异步的) 我的客户端将消息发送到服务器,服务器看到它并回答但我的客户端从未收到欢迎消息。
否则,当我关闭服务器时,客户端会收到欢迎消息。
这是我的服务器代码:
主文件
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server(io_service, 7171);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
tcp_server
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service, int port) // (1)
: m_acceptor(io_service, tcp::endpoint(tcp::v4(), port))
{
std::cout << "Port : " << port << std::endl;
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection = tcp_connection::create(m_acceptor.io_service());
m_acceptor.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) // (4)
{
if (!error)
{
std::cout << "Get one client!" << std::endl;
new_connection->start();
start_accept(); // (5)
}
}
tcp::acceptor m_acceptor;
};
tcp_connection
class tcp_connection : public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& ios)
{
pointer new_connection(new tcp_connection(ios) );
return new_connection;
}
tcp::socket& socket()
{
return m_socket;
}
void do_read() // (1)
{
boost::asio::async_read(m_socket, boost::asio::buffer(m_buffer), // (3)
boost::bind(&tcp_connection::handle_read, shared_from_this(),
boost::asio::placeholders::error)
);
}
void start()
{
m_message = "Welcome on the server \n";
boost::asio::async_write(m_socket, boost::asio::buffer(m_message),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error)
);
}
private:
tcp_connection(boost::asio::io_service& io_service)
: m_socket(io_service)
{ }
void handle_write(const boost::system::error_code& error)
{
std::cout << "handle_write : "<< m_message << std::endl;
if (!error)
do_read(); // (2)
else
std::cout << error.message() << std::endl;
}
void handle_read(const boost::system::error_code& error) // (6)
{
std::cout << "handle read" << m_buffer.data() <<std::endl;
if (!error)
do_read();
else
close();
}
void close() // (7)
{
m_socket.close();
}
tcp::socket m_socket;
std::string m_message;
boost::array<char, 128> m_buffer;
};
我不明白为什么?我怎样才能避免这种情况?