Skip to content

Commit

Permalink
Added async WebSocket example
Browse files Browse the repository at this point in the history
  • Loading branch information
w-henderson committed Feb 10, 2022
1 parent 28e9989 commit 25cfd41
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .github/workflows/examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ jobs:
toolchain: stable
override: true

- name: Check async WebSocket example
uses: actions-rs/cargo@v1
with:
command: check
args: --manifest-path examples/async-websocket/Cargo.toml

- name: Check auth example
uses: actions-rs/cargo@v1
with:
Expand Down
11 changes: 11 additions & 0 deletions examples/async-websocket/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "async_websocket"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
humphrey_ws = { path = "../../humphrey-ws" }

[workspace]
42 changes: 42 additions & 0 deletions examples/async-websocket/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use humphrey_ws::async_app::{AsyncSender, AsyncStream, AsyncWebsocketApp};
use humphrey_ws::message::Message;

use std::io::BufRead;
use std::sync::Arc;
use std::thread::spawn;

fn main() {
// Create a new async WebSocket app with no state, and register some handlers.
let websocket_app: AsyncWebsocketApp<()> = AsyncWebsocketApp::new()
.with_connect_handler(connect_handler)
.with_message_handler(message_handler);

// Get a sender from the app so we can send messages without waiting for events.
// Start a thread to listen for user input.
let sender = websocket_app.sender();
spawn(move || user_input(sender));

// Run the app.
websocket_app.run();
}

/// Listen for user input and broadcast it line by line to all connected clients.
fn user_input(sender: AsyncSender) {
let stdin = std::io::stdin();
let handle = stdin.lock();

for line in handle.lines().flatten() {
sender.broadcast(Message::new(line));
}
}

/// Handle connections by broadcasting their arrival.
fn connect_handler(stream: AsyncStream, _: Arc<()>) {
let message = Message::new(format!("Welcome, {}!", stream.peer_addr()));
stream.broadcast(message);
}

/// Echo messages back to the client that sent them.
fn message_handler(stream: AsyncStream, message: Message, _: Arc<()>) {
stream.send(message);
}

0 comments on commit 25cfd41

Please sign in to comment.