【问题标题】:threads for tcp communicationtcp 通信线程
【发布时间】:2013-02-15 05:27:20
【问题描述】:

我的问题是关于线程的使用。我正在制作一个通过 TCP/IP 连接到设备的应用程序。我正在使用 boost::asio lib。我决定使用读取或侦听线程和写入线程分别用于侦听和写入设备。我的困惑是创建处理通信的套接字的函数也应该是一个线程。 谢谢:)

【问题讨论】:

    标签: c++ multithreading tcp boost-asio


    【解决方案1】:

    在我的客户端类中,我创建了 2 个工作线程来处理发送和接收消息,这些消息用于与多个服务器的多个连接。创建这 2 个工作线程的线程恰好是用户界面线程。这是我的代码的样子:

    // Create the resolver and query objects to resolve the host name in serverPath to an ip address.
    boost::asio::ip::tcp::resolver resolver(*IOService);
    boost::asio::ip::tcp::resolver::query query(serverPath, port);
    boost::asio::ip::tcp::resolver::iterator EndpointIterator = resolver.resolve(query);
    // Set up an SSL context.
    boost::asio::ssl::context ctx(*IOService, boost::asio::ssl::context::tlsv1_client);
    // Specify to not verify the server certificiate right now.
    ctx.set_verify_mode(boost::asio::ssl::context::verify_none);
    // Init the socket object used to initially communicate with the server.
    pSocket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(*IOService, ctx);
    //
    // The thread we are on now, is most likely the user interface thread.  Create a thread to handle all incoming socket work messages.
    if (!RcvThreadCreated)
    {
       WorkerThreads.create_thread(boost::bind(&SSLSocket::RcvWorkerThread, this));
       RcvThreadCreated = true;
       WorkerThreads.create_thread(boost::bind(&SSLSocket::SendWorkerThread, this));
     }
     // Try to connect to the server.  Note - add timeout logic at some point.
     boost::asio::async_connect(pSocket->lowest_layer(), EndpointIterator,
        boost::bind(&SSLSocket::HandleConnect, this, boost::asio::placeholders::error));
    

    工作线程处理所有套接字 I/O。这取决于您在做什么,但是需要从另一个线程创建用于服务套接字的 2 个工作线程。如果您愿意,另一个线程可以是用户界面线程或主线程,因为它会很快返回。如果您与服务器或客户端有多个连接,则由您决定是否需要一组以上的线程来为它们提供服务。

    【讨论】:

    • 谢谢@Bob Bryan。我想我从你的帖子中得到了解决方案:)
    【解决方案2】:

    这取决于你是否想同时读写。在这种情况下,您需要一个线程用于读取和一个线程用于写入,但您必须正确同步这些线程,以防进出设备的两个流相互关联(它们可能会做什么)。但是,在我看来,与设备交谈就像是建立连接、发送一些请求、等待并阅读答案、发送另一个请求、等待并阅读下一个答案等的任务。在这种情况下,只使用一个线程就足够了,让你的生活更轻松。

    【讨论】:

    • 感谢您的回复..我正在使用的这个设备还可以连接到多个客户端,所以当它进行更新时,它会广播状态更新,所以我想,我需要一个线程正在监听它.. 但是套接字的创建和写入呢......
    • 在这种情况下,您需要提供更多关于您正在尝试做什么的信息。例如,在服务器应用程序中,您经常为每个客户端创建一个线程,然后该线程处理与该客户端的连接,并在客户端断开连接时终止。如果您有多个客户端只等待状态更新,您可以只使用一个线程来执行此操作:为客户端保留一个包含套接字的列表,并且每次您想向每个客户端发送一些东西时,您遍历该列表并发送消息一个接一个的客户。
    猜你喜欢
    • 2017-05-22
    • 2014-01-07
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2013-11-07
    • 2013-01-05
    相关资源
    最近更新 更多