Created
October 14, 2021 23:28
-
-
Save PhotonQuantum/f250bb8a2fd0fbba071a65fd7563fd44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::net::TcpListener; | |
use std::sync::mpsc::{channel, Sender}; | |
use std::thread; | |
use std::time::Duration; | |
use futures_util::{SinkExt, StreamExt}; | |
use tungstenite::accept; | |
use tungstenite::Message; | |
fn block_client() { | |
tokio::runtime::Runtime::new().unwrap().block_on(tokio_client()); | |
} | |
async fn async_client() { | |
let (ws, _) = async_tungstenite::tokio::connect_async("ws://127.0.0.1:9001").await.unwrap(); | |
let mut counter = 0; | |
let (mut tx, mut rx) = ws.split(); | |
tokio::spawn(async move { | |
loop { | |
tx.send(Message::Text(format!("hello {}", counter))).await.unwrap(); | |
counter += 1; | |
tokio::time::sleep(Duration::from_secs(1)).await; | |
} | |
}); | |
while let Some(msg) = rx.next().await { | |
println!("received msg: {:?}", msg.unwrap()); | |
} | |
} | |
async fn tokio_client() { | |
let (ws, _) = tokio_tungstenite::connect_async("ws://127.0.0.1:9001").await.unwrap(); | |
let mut counter = 0; | |
let (mut tx, mut rx) = ws.split(); | |
tokio::spawn(async move { | |
loop { | |
tx.send(tokio_tungstenite::tungstenite::Message::Text(format!("hello {}", counter))).await.unwrap(); | |
counter += 1; | |
tokio::time::sleep(Duration::from_secs(1)).await; | |
} | |
}); | |
while let Some(msg) = rx.next().await { | |
println!("received msg: {:?}", msg.unwrap()); | |
} | |
} | |
fn server(sender: Sender<()>) { | |
let server = TcpListener::bind("127.0.0.1:9001").unwrap(); | |
sender.send(()).unwrap(); | |
for stream in server.incoming() { | |
thread::spawn(move || { | |
let mut websocket = accept(stream.unwrap()).unwrap(); | |
loop { | |
let msg = websocket.read_message().unwrap(); | |
// We do not want to send back ping/pong messages. | |
if msg.is_binary() || msg.is_text() { | |
websocket.write_message(msg).unwrap(); | |
} | |
} | |
}); | |
} | |
} | |
fn main() { | |
let (sender, receiver) = channel(); | |
let server = thread::spawn(move || { server(sender) }); | |
receiver.recv().unwrap(); | |
let client = thread::Builder::new().stack_size(110 * 1024).spawn(block_client).unwrap(); | |
client.join().unwrap(); | |
server.join().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment