不能通过asio将消息写入服务器两次以上

Cannot write the message to the server more than two times by asio

本文关键字:两次 服务器 asio 消息 不能      更新时间:2023-10-16

在对这个页面进行了一些调查之后,我尝试编写一个小程序,将消息写入用python脚本开发的本地服务器。到目前为止一切顺利,问题是我只能将消息写入服务器一次。

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>
std::string input;
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::socket sock(io_service);
boost::array<char, 4096> buffer;
void connect_handler(const boost::system::error_code &ec)
{
    if(!ec){
        boost::asio::write(sock, boost::asio::buffer(input));
    }
}
void resolve_handler(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it)
{
    if (!ec){
        sock.async_connect(*it, connect_handler);
    }
}
void write_to_server(std::string const &message)
{
    boost::asio::ip::tcp::resolver::query query("127.0.0.1", "9999");
    input = message;
    resolver.async_resolve(query, resolve_handler);
    io_service.run();
}
int main()
{
    write_to_server("123");
    write_to_server("456");
}
以下是python脚本
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.
    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())     
if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

您的io_service在两个用途之间不是reset

如果您想在停止后再次使用相同的io_service,则必须调用reset成员函数。

write_to_server("123");
io_service.reset();
write_to_server("456");

说,这不是最好的方法来设计整个东西,您应该使用相同的io_service从未停止,但由于run io_service成员函数将主循环程序,你需要发送你的消息一个又一个正确连接回调,或创造某种事件驱动的程序,你发送消息基于用户的输入(如读stdin或一个套接字等)。但是,只有在开发更大更复杂的程序时才应该考虑这一点。