Skip to content

Commit

Permalink
Refactor payload code
Browse files Browse the repository at this point in the history
It turns out that using the `write!` macro on TCP sockets is a bad idea,
as the macro will perform multiple unbuffered writes on the socket.
Formatting into a `Vec` instead results in just one TCP write per loop,
which speeds up communication between the server and the OJD client
  • Loading branch information
FenrirWolf committed Apr 24, 2022
1 parent e4e687b commit f4cac98
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mister_ojd_server"
version = "1.0.1"
version = "1.0.2"
authors = ["Fenrir <[email protected]>"]
edition = "2018"
license = "MIT OR Apache-2.0"
Expand Down
14 changes: 9 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn main() {
}

let payload = gamepad.build_json_payload();
if let Err(e) = write!(&mut socket, "{}#{}", payload.len(), payload) {
if let Err(e) = socket.write(&payload) {
println!("Unable to send payload to Open Joystick Display: {}", e);
}
}
Expand Down Expand Up @@ -207,14 +207,14 @@ impl Gamepad {
Ok(())
}

fn build_json_payload(&mut self) -> String {
fn build_json_payload(&mut self) -> Vec<u8> {
let buttons_json: Vec<Value> = self
.buttons
.iter()
.map(|&value| json!({"pressed": value !=0f64, "value": value}))
.collect();

let payload = json!(
let json = json!(
{
"axes": self.axes,
"buttons": buttons_json,
Expand All @@ -224,8 +224,12 @@ impl Gamepad {
"mapping": "",
"timestamp": 0,
}
);
)
.to_string();

payload.to_string()
let mut payload = Vec::new();
let _ = write!(&mut payload, "{}#{}", json.len(), json);

payload
}
}

0 comments on commit f4cac98

Please sign in to comment.