Skip to content
簡煒航 (Jian Weihang) edited this page Jan 28, 2019 · 1 revision

Rust Echo Server Example

// echo.rs

use std::io;
use std::io::prelude::*;

fn main(){
  loop {
    let mut msg = String::new();
    io::stdin().read_line(&mut msg).expect("Failed to read line");
    print!("{}", msg);
    io::stdout().flush().ok().expect("Could not flush stdout");
  }
}
$ rustc echo.rs && websocketd  --port=8080 ./echo
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Rust Echo Server Example</title>
  </head>
  <body>
    <input type="text" id="input" autofocus />
    <pre id="output"></pre>
    <script>
      const ws = new WebSocket("ws://localhost:8080/");
      const input = document.getElementById("input");
      const output = document.getElementById("output");

      input.onchange = ({ target: { value } }) => {
        ws.send(value);
        input.value = "";
      };

      ws.onmessage = ({ data: msg }) =>
        output.appendChild(document.createTextNode(`${msg}\n`));
    </script>
  </body>
</html>
Clone this wiki locally