Commit de6e3b16 authored by Hugo Trentesaux's avatar Hugo Trentesaux

first rust commit

parents
/target
**/*.rs.bk
\ No newline at end of file
This diff is collapsed.
[package]
name = "guess_game"
version = "0.1.0"
authors = ["Hugo Trentesaux <hugo.trentesaux@u-psud.fr>"]
edition = "2018"
[dependencies]
ws = "0.8.0"
rand = "0.6.5"
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Guess through websocket</title>
<style>
.response {
color: blue;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<h1>WebSocket guess Rust application</h1>
<!-- vuejs app template -->
<div id="app">
<span> Please enter a number between 0 and 10 in this field and press 'enter' </span> <br>
<input type="text" v-model="text" v-on:keyup.enter="send" style="width:40em"/> <br>
<span> The server responded: </span> <span class="response"> {{ response }} </span>
</div>
<!-- vuejs app -->
<script>
var app = new Vue({
el: '#app',
data: {
text: undefined,
response: "enter a number",
socket: undefined,
},
computed: {
},
methods: {
send: function () {
this.socket.send(this.text);
},
openSocket: function () { // set websocket
this.socket = new WebSocket("ws://127.0.0.1:3012/");
this.socket.onmessage = function (event) {
app.response = event.data // store message it in response
}
}
},
})
app.openSocket(); // initialize connection
</script>
</body>
</html>
extern crate ws; // WebSocket crate
use rand::Rng;
use std::cmp::Ordering; // ordering // random
fn main() {
// generate random number
let secret_number: u32 = rand::thread_rng().gen_range(0, 10);
// run websocket server
let _srv = ws::listen("127.0.0.1:3012", |out| {
// closure passed to websocket listen function
move |guess: ws::Message| {
// defines a response
let response: &str = match guess.into_text() {
// convert input into text
Ok(guess) => match guess.trim().parse::<u32>() {
// convert text into number
Ok(guess) => match guess.cmp(&secret_number) {
// compare number to generated
Ordering::Less => "Too low",
Ordering::Greater => "Too high",
Ordering::Equal => "you found !",
},
Err(_) => "not valid",
},
Err(_) => "not text",
};
out.send(response) // send response to websocket
}
});
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment