Skip to content
On this page

presentation: width: 1024 height: 800

需求

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

数据结构定义

rust
#[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
rust
 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
rust
 async fn client_task(self, mut reader: ReadHalf<TcpStream>) {}

实现-3

process_error

  1. 删除所有订阅
  2. 关闭连接
rust
 async fn process_error<E: Error>(&self, 
    err: E, subs: HashMap<String, ArcSubscription>) {}

实现-4

process_sub 登记到全局表中

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

实现-5

  1. 查找所有的订阅
  2. 将消息逐一转发给他们
rust
async fn process_pub(&self, pub_arg: &PubArg<'_>) -> crate::error::Result<()> {}

实现-6

发送消息

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