无法通过asio将消息写入服务器两次以上

时间:2014-08-11 07:37:22

标签: python c++ boost boost-asio

在对this page进行一些调查之后,我尝试编写一个小程序将消息写入由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()

1 个答案:

答案 0 :(得分:1)

io_service在两次使用之间不是reset

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

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

也就是说,这不是设计这些内容的最佳方式,您可能应该使用相同的io_service并且永远不会停止它,但是因为run的{​​{1}}成员函数将是您程序的主循环,您必须在连接回调中一个接一个地发送消息,或创建某种事件驱动程序,您可以根据用户输入发送消息(例如,读取在stdin或插座等)。但是,只有在你开发更大更复杂的程序时才应考虑这一点。