从零实现消息中间件-server.client


presentation:
width: 1024

height: 800

需求

  1. 接收消息
  2. sub 记录到全局列表中
  3. pub发送给相关订阅
  4. 出错,关闭连接,删除订阅
  5. 发送MSG


数据结构定义

#[derive(Debug)]
pub struct Client<T: SubListTrait> {
    pub srv: Arc<Mutex<ServerState<T>>>,
    pub cid: u64,
    pub msg_sender: Arc<Mutex<ClientMessageSender>>,
}
#[derive(Debug)]
pub struct ClientMessageSender {
    writer: WriteHalf<TcpStream>,
}

实现

process_connection

  • 创建Client以及可以共享使用的ClientMessageSender
  • 启动client_task

    impl<T: SubListTrait + Send + 'static> Client<T> {
    
    pub fn process_connection(
        cid: u64,
        srv: Arc<Mutex<ServerState<T>>>,
        conn: TcpStream,
    ) -> Arc<Mutex<ClientMessageSender>> {}
         
    ...
    }
    

    实现-2

  • 读取,解析消息

  • 分发消息给相应的处理函数

    • process_error
    • process_sub
    • process_pub

      async fn client_task(self, mut reader: ReadHalf<TcpStream>) {}
      

      实现-3

      process_error

    • 删除所有订阅

    • 关闭连接

      async fn process_error<E: Error>(&self, 
      err: E, subs: HashMap<String, ArcSubscription>) {}
      

      实现-4

      process_sub
      登记到全局表中

      async fn process_sub(
      &self,
      sub: &SubArg<'_>,
      subs: &mut HashMap<String, ArcSubscription>,
      ) -> crate::error::Result<()> {}
      

实现-5

  1. 查找所有的订阅
  2. 将消息逐一转发给他们

    async fn process_pub(&self, pub_arg: &PubArg<'_>) -> crate::error::Result<()> {}
    

    实现-6

    发送消息

    async fn send_message(&self, 
    sub: &Subscription, pub_arg: &PubArg<'_>) 
      -> std::io::Result<()> {}