{"title":"WebSockets in Rust","url":"https://seanbehan.ca/posts/websockets-rust","description":"Part one of a Rust series: a WebSocket server built on the ws crate.","author":"Sean Behan","published":"2019-11-27T02:56:22.000Z","updated":null,"draft":false,"tags":["programming","rust","websocket"],"readingMinutes":2,"image":null,"sections":[{"id":"introduction","text":"Introduction","level":2},{"id":"project-setup","text":"Project Setup","level":2},{"id":"building-the-websocket-server","text":"Building the WebSocket Server","level":2},{"id":"handling-messages","text":"Handling Messages","level":2},{"id":"testing-the-server","text":"Testing the Server","level":2},{"id":"next-steps","text":"Next Steps","level":2}],"content_format":"text/markdown","content_url":"https://seanbehan.ca/posts/websockets-rust.md","content":"### Introduction\n\nToday I'll show you how you can write incredibly fast code in Rust. This is\n\npart one of a tutorial series.\n\nThis is an intermediate tutorial, if you are unfamiliar with Rust basics I\n\nwould suggest reading the Rust book for free at [https://doc.rust-lang.org/stable/book/](https://doc.rust-lang.org/stable/book/).\n\n### Project Setup\n\nLets dive right in.\n\n```bash\ncargo new rust-tutorial\ncd rust-tutorial\n```\n\nLet's build our websocket server.\n\nEdit your `Cargo.toml` and add [`ws`](https://docs.rs/ws/) to your\n\n`[dependencies]`.\n\nYour `Cargo.toml` should now look something like this.\n\n```toml\n[package]\nname = \"rust-tutorial\"\nversion = \"0.1.0\"\nauthors = [\"Sean Behan <codebam@riseup.net>\"]\nedition = \"2018\"\n\n[dependencies]\nws = \"*\"\n```\n\n### Building the WebSocket Server\n\nImport our libraries.\n\n```rust\nuse ws::listen;\n```\n\nStart a websocket listener.\n\n```rust\nfn main() {\n    listen(\"127.0.0.1:5000\", |out| {\n        move |msg: ws::Message| {\n            // handle the msg here\n        }\n    }\n}\n```\n\n### Handling Messages\n\nWe'll respond to recieved messages and just echo them back for now.\n\nOf course you could easily pass this data into any function and use it to\n\ngenerate a response. In fact the incoming and outgoing data doesn't even have\n\nto be text.\n\n```rust\nout.send(format!(\"recieved message: {}\", msg.into_text().unwrap())).unwrap();\nout.close(ws::CloseCode::Normal)\n```\n\n### Testing the Server\n\nIf we connect to this now using websocat, which can be installed with `cargo\n\ninstall websocat`, we can see the server echos back messages that we send to\n\nit.\n\n```sh\n$ websocat ws://127.0.0.1:5000\nhello world\nrecieved message: hello world\n```\n\nThis isn't that interesting. It's cool that we can do all this in just 8 lines\n\nof Rust though!\n\n### Next Steps\n\nIn the next part of this series I'll show you how to use use\n\n[`tokio`](https://docs.rs/tokio/) to create an asyncronous server so we can\n\nmanage simultaneous connections. Stay tuned!\n"}