pub struct SideB<Req, Resp> { /* private fields */ }Expand description
Side B endpoint (request receiver, response sender) - single instance
B 方的 channel 端点(请求接收方,响应发送方)- 单实例
Implementations§
Source§impl<Req, Resp> SideB<Req, Resp>
impl<Req, Resp> SideB<Req, Resp>
Sourcepub async fn recv_request(
&self,
) -> Result<RequestGuard<Req, Resp>, ChannelError>
pub async fn recv_request( &self, ) -> Result<RequestGuard<Req, Resp>, ChannelError>
Wait for and receive next request, returning a guard that must be replied to
The returned RequestGuard enforces that you must call reply() on it.
If you drop the guard without calling reply(), it will panic.
等待并接收下一个请求,返回一个必须回复的 guard
返回的 RequestGuard 强制你必须调用 reply()。
如果你在没有调用 reply() 的情况下丢弃 guard,会 panic。
§Returns
Ok(RequestGuard): Received request from a side AErr(ChannelError::Closed): All side A instances have been closed
§Example
let (side_a, side_b) = channel::<String, i32>();
tokio::spawn(async move {
while let Ok(guard) = side_b.recv_request().await {
let len = guard.request().len() as i32;
guard.reply(len);
}
});
let response = side_a.request("Hello".to_string()).await;
assert_eq!(response, Ok(5));Sourcepub async fn handle_request<F>(&self, handler: F) -> Result<(), ChannelError>
pub async fn handle_request<F>(&self, handler: F) -> Result<(), ChannelError>
Convenient method to handle request and send response
This method will:
- Wait for and receive request
- Call the handler function
- Send the response via the guard
处理请求并发送响应的便捷方法
这个方法会:
- 等待并接收请求
- 调用处理函数
- 通过 guard 发送响应
§Example
let (side_a, side_b) = channel::<String, i32>();
tokio::spawn(async move {
while side_b.handle_request(|req| req.len() as i32).await.is_ok() {
// Continue handling
}
});
let response = side_a.request("Hello".to_string()).await;
assert_eq!(response, Ok(5));Sourcepub async fn handle_request_async<F, Fut>(
&self,
handler: F,
) -> Result<(), ChannelError>
pub async fn handle_request_async<F, Fut>( &self, handler: F, ) -> Result<(), ChannelError>
Convenient async method to handle request and send response
Similar to handle_request, but supports async handler functions.
Note: The handler takes ownership of the request to avoid lifetime issues.
处理请求并发送响应的异步便捷方法
与 handle_request 类似,但支持异步处理函数。
注意:处理函数会获取请求的所有权以避免生命周期问题。
§Example
let (side_a, side_b) = channel::<String, String>();
tokio::spawn(async move {
while side_b.handle_request_async(|req| async move {
// Async processing - req is owned
req.to_uppercase()
}).await.is_ok() {
// Continue handling
}
});
let response = side_a.request("hello".to_string()).await;
assert_eq!(response, Ok("HELLO".to_string()));