pub trait UserConnection: Send + Sync {
type Input: Send + 'static;
type Output: Send + 'static;
// Required methods
fn receive<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Self::Input, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait,
Self: 'async_trait;
fn try_receive<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Option<Self::Input>, Error>> + Send + 'async_trait>>
where 'life0: 'async_trait,
Self: 'async_trait;
fn send<'life0, 'async_trait>(
&'life0 self,
output: Self::Output,
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait,
Self: 'async_trait;
fn is_connected(&self) -> bool;
// Provided method
fn close<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where 'life0: 'async_trait,
Self: 'async_trait { ... }
}Expand description
用户连接Trait
定义秘书与用户之间的通信接口。 不同的连接方式(WebSocket、TCP、Channel等)都可以实现这个trait。
§类型参数
Input: 用户发送的输入类型Output: 秘书发送的输出类型
§示例
ⓘ
struct WebSocketConnection {
ws: WebSocket,
}
#[async_trait]
impl UserConnection for WebSocketConnection {
type Input = UserMessage;
type Output = SecretaryResponse;
async fn receive(&self) -> anyhow::Result<Self::Input> {
let msg = self.ws.recv().await?;
Ok(serde_json::from_str(&msg)?)
}
async fn send(&self, output: Self::Output) -> anyhow::Result<()> {
self.ws.send(serde_json::to_string(&output)?).await?;
Ok(())
}
fn is_connected(&self) -> bool {
self.ws.is_open()
}
}Required Associated Types§
Required Methods§
Sourcefn receive<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Self::Input, Error>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
fn receive<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Self::Input, Error>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
接收用户输入(阻塞)
Sourcefn try_receive<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Option<Self::Input>, Error>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
fn try_receive<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Option<Self::Input>, Error>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
尝试接收用户输入(非阻塞)
返回 Ok(Some(input)) 表示收到输入
返回 Ok(None) 表示没有可用输入
返回 Err(e) 表示发生错误
Sourcefn send<'life0, 'async_trait>(
&'life0 self,
output: Self::Output,
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
fn send<'life0, 'async_trait>(
&'life0 self,
output: Self::Output,
) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
发送输出给用户
Sourcefn is_connected(&self) -> bool
fn is_connected(&self) -> bool
检查连接是否有效