Skip to content

Commit 25cfd41

Browse files
committed
Added async WebSocket example
1 parent 28e9989 commit 25cfd41

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

.github/workflows/examples.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ jobs:
2525
toolchain: stable
2626
override: true
2727

28+
- name: Check async WebSocket example
29+
uses: actions-rs/cargo@v1
30+
with:
31+
command: check
32+
args: --manifest-path examples/async-websocket/Cargo.toml
33+
2834
- name: Check auth example
2935
uses: actions-rs/cargo@v1
3036
with:

examples/async-websocket/Cargo.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[package]
2+
name = "async_websocket"
3+
version = "0.1.0"
4+
edition = "2018"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]
9+
humphrey_ws = { path = "../../humphrey-ws" }
10+
11+
[workspace]

examples/async-websocket/src/main.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use humphrey_ws::async_app::{AsyncSender, AsyncStream, AsyncWebsocketApp};
2+
use humphrey_ws::message::Message;
3+
4+
use std::io::BufRead;
5+
use std::sync::Arc;
6+
use std::thread::spawn;
7+
8+
fn main() {
9+
// Create a new async WebSocket app with no state, and register some handlers.
10+
let websocket_app: AsyncWebsocketApp<()> = AsyncWebsocketApp::new()
11+
.with_connect_handler(connect_handler)
12+
.with_message_handler(message_handler);
13+
14+
// Get a sender from the app so we can send messages without waiting for events.
15+
// Start a thread to listen for user input.
16+
let sender = websocket_app.sender();
17+
spawn(move || user_input(sender));
18+
19+
// Run the app.
20+
websocket_app.run();
21+
}
22+
23+
/// Listen for user input and broadcast it line by line to all connected clients.
24+
fn user_input(sender: AsyncSender) {
25+
let stdin = std::io::stdin();
26+
let handle = stdin.lock();
27+
28+
for line in handle.lines().flatten() {
29+
sender.broadcast(Message::new(line));
30+
}
31+
}
32+
33+
/// Handle connections by broadcasting their arrival.
34+
fn connect_handler(stream: AsyncStream, _: Arc<()>) {
35+
let message = Message::new(format!("Welcome, {}!", stream.peer_addr()));
36+
stream.broadcast(message);
37+
}
38+
39+
/// Echo messages back to the client that sent them.
40+
fn message_handler(stream: AsyncStream, message: Message, _: Arc<()>) {
41+
stream.send(message);
42+
}

0 commit comments

Comments
 (0)