MCPcopy Index your code
hub / github.com/bedroombuilds/python2rust / main

Function main

23_websockets_client/rust/ws_client/src/main.rs:9–63  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

7
8#[tokio::main]
9async fn main() {
10 let connect_addr = "ws://localhost:8000/chat";
11 let url = url::Url::parse(&connect_addr).unwrap();
12 let (mut ws_stream, _) = connect_async(url).await.expect("Failed to connect");
13 println!("WebSocket handshake has been successfully completed");
14
15 let (mut tx_stdin, mut rx) = mpsc::channel::<String>(10);
16 // read from stdin
17 let stdin_loop = async move {
18 loop {
19 let mut line = String::new();
20 let mut buf_stdin = tokio::io::BufReader::new(tokio::io::stdin());
21 buf_stdin.read_line(&mut line).await.unwrap();
22 tx_stdin.send(line.trim().to_string()).await.unwrap();
23 if line.trim() == "/exit" {
24 break;
25 }
26 }
27 };
28 tokio::task::spawn(stdin_loop);
29 // handle websocket messages
30 loop {
31 tokio::select! {
32 ws_msg = ws_stream.next() => {
33 match ws_msg {
34 Some(msg) => match msg {
35 Ok(msg) => match msg {
36 Message::Binary(x) => println!("binary {:?}", x),
37 Message::Text(x) => println!("{}", x),
38 Message::Ping(x) => println!("Ping {:?}", x),
39 Message::Pong(x) => println!("Pong {:?}", x),
40 Message::Close(x) => println!("Close {:?}", x),
41 },
42 Err(_) => {println!("server went away"); break;}
43 },
44 None => {println!("no message"); break;},
45 }
46 },
47 stdin_msg = rx.next() => {
48 match stdin_msg {
49 Some(msg) => {
50 let _ = ws_stream.send(Message::Text(msg)).await;
51 },
52 None => break
53 }
54 }
55 };
56 }
57 // Gracefully close connection by Close-handshake procedure
58 let _ = ws_stream.send(Message::Close(None)).await;
59 let close = ws_stream.next().await;
60 println!("server close msg: {:?}", close);
61 assert!(ws_stream.next().await.is_none());
62 let _ = ws_stream.close(None).await;
63}

Callers

nothing calls this directly

Calls 3

read_lineMethod · 0.80
sendMethod · 0.80
nextMethod · 0.45

Tested by

no test coverage detected