Skip to main content

SocketServerHandle

Struct SocketServerHandle 

Source
pub struct SocketServerHandle { /* private fields */ }

Implementations§

Source§

impl SocketServerHandle

Source

pub fn spawn(config: RealtimeConfig) -> Self

Examples found in repository?
examples/chat_demo.rs (line 72)
68async fn main() -> Result<(), Box<dyn std::error::Error>> {
69    let users = demo_users();
70    let verifier = StaticTokenVerifier::new(&users);
71
72    let server_handle = SocketServerHandle::spawn(Default::default());
73
74    server_handle.on_message("room:lobby", |payload| {
75        println!("Got the payload: {}", payload)
76    });
77
78    let socket_app_state = Arc::new(SocketAppState::new(server_handle, verifier));
79
80    let app = Router::new()
81        .route("/", get(index))
82        .route("/demo/users", get(demo_users_handler))
83        .nest("/api/v1", realtime::server::axum::router(socket_app_state));
84
85    let addr = demo_addr();
86    println!("realtime demo listening on http://{addr}");
87    println!("open http://{addr} in your browser");
88
89    let listener = tokio::net::TcpListener::bind(addr).await?;
90    axum::serve(listener, app).await?;
91    Ok(())
92}
More examples
Hide additional examples
examples/drawing_demo.rs (line 110)
107async fn main() -> Result<(), Box<dyn std::error::Error>> {
108    let users = demo_users();
109    let verifier = StaticTokenVerifier::new(&users);
110    let socket_server_handle = SocketServerHandle::spawn(Default::default());
111    let board_store = BoardStore::default();
112
113    {
114        let server = socket_server_handle.clone();
115        let board_store = board_store.clone();
116        socket_server_handle.on_events(move |channel, event, payload| {
117            if !channel.starts_with("board:") {
118                return;
119            }
120
121            match event.as_str() {
122                STROKE_EVENT => {
123                    board_store.append_chunk(&channel, payload);
124                }
125                BOARD_CLEARED_EVENT => {
126                    board_store.clear_board(&channel);
127                }
128                SYNC_REQUEST_EVENT => {
129                    let Some(requester_user_id) = payload
130                        .get("requester_user_id")
131                        .and_then(Value::as_str)
132                        .map(str::trim)
133                        .filter(|value| !value.is_empty())
134                        .map(|value| value.to_string())
135                    else {
136                        return;
137                    };
138
139                    let chunks = board_store.snapshot(&channel);
140                    let chunk_count = chunks.len();
141                    let snapshot_payload = json!({
142                        "board_channel": channel,
143                        "snapshot_version": 1,
144                        "chunk_count": chunk_count,
145                        "chunks": chunks,
146                    });
147
148                    let server = server.clone();
149                    tokio::spawn(async move {
150                        if let Err(err) = server
151                            .send_event_to_user(
152                                requester_user_id,
153                                SYNC_SNAPSHOT_EVENT,
154                                snapshot_payload,
155                            )
156                            .await
157                        {
158                            eprintln!("failed to send board snapshot: {err}");
159                        }
160                    });
161                }
162                _ => {}
163            }
164        });
165    }
166
167    let socket_app_state = Arc::new(SocketAppState::new(socket_server_handle, verifier));
168
169    let app = Router::new()
170        .route("/", get(index))
171        .route("/demo/users", get(demo_users_handler))
172        .nest("/api/v1", realtime::server::axum::router(socket_app_state));
173
174    let addr = demo_addr();
175    println!("realtime drawing demo listening on http://{addr}");
176    println!("open http://{addr} in your browser");
177
178    let listener = tokio::net::TcpListener::bind(addr).await?;
179    axum::serve(listener, app).await?;
180    Ok(())
181}
Source

pub fn spawn_with_policy( config: RealtimeConfig, policy: Arc<dyn ChannelPolicy>, ) -> Self

Source

pub fn disabled(config: RealtimeConfig) -> Self

Source

pub fn is_enabled(&self) -> bool

Source

pub fn max_message_bytes(&self) -> usize

Source

pub async fn serve_socket(&self, socket: WebSocket, auth: SessionAuth)

Source

pub async fn send( &self, channel_name: impl Into<Channel>, message: Payload, ) -> Result<(), RealtimeError>

Source

pub async fn send_to_user( &self, user_id: impl Into<UserId>, message: Payload, ) -> Result<(), RealtimeError>

Source

pub async fn send_event( &self, channel_name: impl Into<Channel>, event: impl Into<Event>, payload: Payload, ) -> Result<(), RealtimeError>

Source

pub async fn send_event_to_user( &self, user_id: impl Into<UserId>, event: impl Into<Event>, payload: Payload, ) -> Result<(), RealtimeError>

Examples found in repository?
examples/drawing_demo.rs (lines 151-155)
107async fn main() -> Result<(), Box<dyn std::error::Error>> {
108    let users = demo_users();
109    let verifier = StaticTokenVerifier::new(&users);
110    let socket_server_handle = SocketServerHandle::spawn(Default::default());
111    let board_store = BoardStore::default();
112
113    {
114        let server = socket_server_handle.clone();
115        let board_store = board_store.clone();
116        socket_server_handle.on_events(move |channel, event, payload| {
117            if !channel.starts_with("board:") {
118                return;
119            }
120
121            match event.as_str() {
122                STROKE_EVENT => {
123                    board_store.append_chunk(&channel, payload);
124                }
125                BOARD_CLEARED_EVENT => {
126                    board_store.clear_board(&channel);
127                }
128                SYNC_REQUEST_EVENT => {
129                    let Some(requester_user_id) = payload
130                        .get("requester_user_id")
131                        .and_then(Value::as_str)
132                        .map(str::trim)
133                        .filter(|value| !value.is_empty())
134                        .map(|value| value.to_string())
135                    else {
136                        return;
137                    };
138
139                    let chunks = board_store.snapshot(&channel);
140                    let chunk_count = chunks.len();
141                    let snapshot_payload = json!({
142                        "board_channel": channel,
143                        "snapshot_version": 1,
144                        "chunk_count": chunk_count,
145                        "chunks": chunks,
146                    });
147
148                    let server = server.clone();
149                    tokio::spawn(async move {
150                        if let Err(err) = server
151                            .send_event_to_user(
152                                requester_user_id,
153                                SYNC_SNAPSHOT_EVENT,
154                                snapshot_payload,
155                            )
156                            .await
157                        {
158                            eprintln!("failed to send board snapshot: {err}");
159                        }
160                    });
161                }
162                _ => {}
163            }
164        });
165    }
166
167    let socket_app_state = Arc::new(SocketAppState::new(socket_server_handle, verifier));
168
169    let app = Router::new()
170        .route("/", get(index))
171        .route("/demo/users", get(demo_users_handler))
172        .nest("/api/v1", realtime::server::axum::router(socket_app_state));
173
174    let addr = demo_addr();
175    println!("realtime drawing demo listening on http://{addr}");
176    println!("open http://{addr} in your browser");
177
178    let listener = tokio::net::TcpListener::bind(addr).await?;
179    axum::serve(listener, app).await?;
180    Ok(())
181}
Source

pub async fn emit_to_user( &self, user_id: impl Into<UserId>, event: impl Into<Event>, payload: Payload, ) -> Result<(), RealtimeError>

Source

pub fn on_message<F>(&self, channel: &str, handler: F) -> SubscriptionId
where F: Fn(Payload) + Send + Sync + 'static,

Examples found in repository?
examples/chat_demo.rs (lines 74-76)
68async fn main() -> Result<(), Box<dyn std::error::Error>> {
69    let users = demo_users();
70    let verifier = StaticTokenVerifier::new(&users);
71
72    let server_handle = SocketServerHandle::spawn(Default::default());
73
74    server_handle.on_message("room:lobby", |payload| {
75        println!("Got the payload: {}", payload)
76    });
77
78    let socket_app_state = Arc::new(SocketAppState::new(server_handle, verifier));
79
80    let app = Router::new()
81        .route("/", get(index))
82        .route("/demo/users", get(demo_users_handler))
83        .nest("/api/v1", realtime::server::axum::router(socket_app_state));
84
85    let addr = demo_addr();
86    println!("realtime demo listening on http://{addr}");
87    println!("open http://{addr} in your browser");
88
89    let listener = tokio::net::TcpListener::bind(addr).await?;
90    axum::serve(listener, app).await?;
91    Ok(())
92}
Source

pub fn on_messages<F>(&self, handler: F) -> SubscriptionId
where F: Fn(Channel, Payload) + Send + Sync + 'static,

Source

pub fn on_channel_event<F>(&self, channel: &str, handler: F) -> SubscriptionId
where F: Fn(Event, Payload) + Send + Sync + 'static,

Source

pub fn on_events<F>(&self, handler: F) -> SubscriptionId
where F: Fn(Channel, Event, Payload) + Send + Sync + 'static,

Examples found in repository?
examples/drawing_demo.rs (lines 116-164)
107async fn main() -> Result<(), Box<dyn std::error::Error>> {
108    let users = demo_users();
109    let verifier = StaticTokenVerifier::new(&users);
110    let socket_server_handle = SocketServerHandle::spawn(Default::default());
111    let board_store = BoardStore::default();
112
113    {
114        let server = socket_server_handle.clone();
115        let board_store = board_store.clone();
116        socket_server_handle.on_events(move |channel, event, payload| {
117            if !channel.starts_with("board:") {
118                return;
119            }
120
121            match event.as_str() {
122                STROKE_EVENT => {
123                    board_store.append_chunk(&channel, payload);
124                }
125                BOARD_CLEARED_EVENT => {
126                    board_store.clear_board(&channel);
127                }
128                SYNC_REQUEST_EVENT => {
129                    let Some(requester_user_id) = payload
130                        .get("requester_user_id")
131                        .and_then(Value::as_str)
132                        .map(str::trim)
133                        .filter(|value| !value.is_empty())
134                        .map(|value| value.to_string())
135                    else {
136                        return;
137                    };
138
139                    let chunks = board_store.snapshot(&channel);
140                    let chunk_count = chunks.len();
141                    let snapshot_payload = json!({
142                        "board_channel": channel,
143                        "snapshot_version": 1,
144                        "chunk_count": chunk_count,
145                        "chunks": chunks,
146                    });
147
148                    let server = server.clone();
149                    tokio::spawn(async move {
150                        if let Err(err) = server
151                            .send_event_to_user(
152                                requester_user_id,
153                                SYNC_SNAPSHOT_EVENT,
154                                snapshot_payload,
155                            )
156                            .await
157                        {
158                            eprintln!("failed to send board snapshot: {err}");
159                        }
160                    });
161                }
162                _ => {}
163            }
164        });
165    }
166
167    let socket_app_state = Arc::new(SocketAppState::new(socket_server_handle, verifier));
168
169    let app = Router::new()
170        .route("/", get(index))
171        .route("/demo/users", get(demo_users_handler))
172        .nest("/api/v1", realtime::server::axum::router(socket_app_state));
173
174    let addr = demo_addr();
175    println!("realtime drawing demo listening on http://{addr}");
176    println!("open http://{addr} in your browser");
177
178    let listener = tokio::net::TcpListener::bind(addr).await?;
179    axum::serve(listener, app).await?;
180    Ok(())
181}
Source

pub fn off(&self, id: SubscriptionId) -> bool

Trait Implementations§

Source§

impl Clone for SocketServerHandle

Source§

fn clone(&self) -> SocketServerHandle

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,