根据包序列id调度响应包

时间:2015-06-22 09:08:40

标签: c++ boost boost-asio

我有一个第三方服务器,我正在为它编写一个dll接口,我的客户端使用我的dll与服务器通信。

协议使用长tcp连接,所有流量都来自此tcp连接。可能会同时发送/接收多个数据包,例如send_msgheart_beat,因此我必须使用 async_write / async_read 来阻止阻塞操作。每个数据包都有其序列ID。例如,我发送一个序列号为== 123的消息,然后我应该等待服务器响应序列号== 123的数据包。

更新:无法保证服务器按顺序响应数据包。如果按AB的顺序发送了两个数据包,则响应顺序可以是response_Bresponse_A。序列ID是识别数据包的唯一方法。

数据包看起来像:

4bytes size   +   2 bytes crc check   +   4 bytes SEQUENCE ID   +   ....

问题在于,使用我的dll的客户更喜欢以阻止方式使用功能,他们不喜欢回调。例如,他们喜欢

bool DLL_EXPORT send_msg(...) {
   // send msg via long_connection, the seq_id==123
   // recv msg via long_connection, just want the packet with seq_id==123 (How?)
   return if_msg_sent_successfully;
}

我使用boost asio,我不知道是否有任何实用类型的boost,或者适合这种情况的设计模式,这是我能提出的解决方案:

// use a global std::map<seq_id, packet_content>
std::map<int, std::string> map_received;

每次收到一个数据包,将seq_idpacket_body写入map_received,send_msg函数看起来像

bool DLL_EXPORT send_msg(...) {
   // async_send msg via long_connection, the seq_id==123
   while(not_time_out) {
       if(map_received.find(123) != map_received.end()) {
           // get the packet and erase the 123 pair
       }
       Sleep(10); // prevent cpu cost
   }
   return if_msg_sent_successfully;
}

这个解决方案很丑陋,必须有更好的设计。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

你可以使用std::promisestd::future(如果你还没有使用C ++ 11,还可以使用他们的强制对手)。

想法是在发送请求时将std::shared_ptr<std::promise<bool>>与当前序列id一起存储为地图中的键。 在阻塞发送功能中,您需要等待相应的std::future<bool>设置。 收到响应数据包后,将从地图中提取相应的std::promise<bool>,并设置值,并且发送功能为“#34; unblocked&#34;”。

以下示例基于Boost asio documentation中的聊天客户端示例,并且不完整(例如,连接部分丢失,标题和正文读取未分割等)。由于它不完整,我没有进行运行时测试,但它应该说明这个想法。

#include <thread>
#include <map>
#include <future> 
#include <iostream>

#include <boost/asio.hpp>

class Message
{
public:
  enum { header_length = 10 };
  enum { max_body_length = 512 };

  Message()
    : body_length_(0)
  {
  }

  const char* data() const
  {
    return data_;
  }

  char* data()
  {
    return data_;
  }

  std::size_t length() const
  {
    return header_length + body_length_;
  }

  const char* body() const
  {
    return data_ + header_length;
  }

  char* body()
  {
    return data_ + header_length;
  }

private:
  char data_[header_length + max_body_length];
  std::size_t body_length_;
};


class Client
{    
public:
    Client(boost::asio::io_service& io_service)
        : io_service(io_service),
          socket(io_service),
          current_sequence_id(0)
    {}

    bool blocking_send(const std::string& msg)
    {
        auto future = async_send(msg);
        // blocking wait
        return future.get();
    }

    void start_reading()
    {
        auto handler = [this](boost::system::error_code ec, std::size_t /*length*/)
                       {
                           if(!ec)
                           {
                               // parse response ...
                               int response_id = 0;
                               auto promise = map_received[response_id];
                               promise->set_value(true);
                               map_received.erase(response_id);
                           }
                       };
        boost::asio::async_read(socket,
                                boost::asio::buffer(read_msg_.data(), Message::header_length),
                                handler);
    }

    void connect()
    {
        // ...
        start_reading();
    }

private:

    std::future<bool> async_send(const std::string& msg)
    {
        auto promise = std::make_shared<std::promise<bool>>();
        auto handler = [=](boost::system::error_code ec, std::size_t /*length*/){std::cout << ec << std::endl;};
        boost::asio::async_write(socket,
                                 boost::asio::buffer(msg),
                                 handler);
        // store promise in map
        map_received[current_sequence_id] = promise;
        current_sequence_id++;
        return promise->get_future();
    }

    boost::asio::io_service& io_service;
    boost::asio::ip::tcp::socket socket;
    std::map<int, std::shared_ptr<std::promise<bool>>> map_received;
    int current_sequence_id;
    Message read_msg_;
};



int main()
{
    boost::asio::io_service io_service;
    Client client(io_service);

    std::thread t([&io_service](){ io_service.run(); });

    client.connect();
    client.blocking_send("dummy1");
    client.blocking_send("dummy2");

    return 0;
}
相关问题