tokio_websocket_client/handler.rs
1use crate::message::CloseCode;
2
3/// Retry strategy to use when connection fails or server close the connection.
4#[derive(Debug, Clone, Eq, PartialEq)]
5pub enum RetryStrategy {
6 /// Retry connecting to the server.
7 Retry,
8 /// Close the connection and end all tasks.
9 Close,
10}
11
12/// Defines how to handle text, binary and close messages from the server.
13///
14/// It also allows to define [`RetryStrategy`] when connection fails and a callback on connection.
15pub trait Handler: Send {
16 /// Handle text messages.
17 ///
18 /// Any error will trigger a reconnection.
19 fn on_text(&mut self, text: &str) -> impl Future<Output = ()> + Send;
20
21 /// Handle binary messages.
22 ///
23 /// Any error will trigger a reconnection.
24 fn on_binary(&mut self, buffer: &[u8]) -> impl Future<Output = ()> + Send;
25
26 /// Defines the behavior for when the server closes the connection.
27 ///
28 /// Return the [`RetryStrategy`] to use.
29 #[allow(unused_variables)]
30 fn on_close(
31 &mut self,
32 code: CloseCode,
33 reason: &str,
34 ) -> impl Future<Output = RetryStrategy> + Send {
35 async move { RetryStrategy::Retry }
36 }
37
38 /// Defines a callback for when connection succeeds.
39 fn on_connect(&mut self) -> impl Future<Output = ()> + Send {
40 async move {}
41 }
42
43 /// Defines the behavior for when the connection fails.
44 ///
45 /// Return the [`RetryStrategy`] to use.
46 fn on_connect_failure(&mut self) -> impl Future<Output = RetryStrategy> + Send {
47 async move { RetryStrategy::Retry }
48 }
49
50 /// Defines a callback for when connection is broken.
51 fn on_disconnect(&mut self) -> impl Future<Output = RetryStrategy> + Send {
52 async move { RetryStrategy::Retry }
53 }
54}