python - asio 无法将消息写入服务器两次以上

标签 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()

最佳答案

您的 io_service 在两次使用之间未被重置

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

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

也就是说,这不是设计这一切的最佳方式,您可能应该使用相同的 io_service 并且永远不要停止它,但是由于 run 成员函数io_service 将是您程序的主循环,您必须在连接回调中一个接一个地发送消息,或者创建某种事件驱动的程序来发送消息基于用户输入(例如在标准输入或套接字上读取等)。但只有在开发更大更复杂的程序时才应考虑这一点。

关于python - asio 无法将消息写入服务器两次以上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25238034/

相关文章:

python - 如何在python中删除数据框中数据列中的0

c++ - 无法使用 makefile 编译

c++ - 在 Boost MultiArray 中访问元素的最快方法

基于 Python 标准的动态函数添加到类中

python - IDLE中奇怪的变量多重赋值python

c++ - 初学者 C++ 练习的解决方案的意外输出

c++ - 来自其他类的 asio 计时器

c++ - boost::function & boost::lambda 再次

python - 当开发服务器运行时(在 Kudu 上),基于 Django 的 Azure Web App 陷入困境

c++ - 在此示例中,指向指针的指针有什么作用?