If you already have expereinece in Rust, you can just clone the Steadylearner Chat GitHub repository.
$yarn in /static/chat folder to download NPM packages and
$cargo run for Rust crates in ws_rs_with_rocket folder.
It will show you the chat app with Rust Backend at http://localhost:8000/chat.
(I just wanted to save your time if you already know how to code.)
- How to install Rust
- Websocket API
- Steadylearner Chat
- Thread in Rust
You will use Rust mainly to build socket server to handle messages. So you need to install it following the instruction from its official website.
You also need to understand what is Websocket API to understand what you need to connect, send, receive and close the websocket for your chat app.
We will use ws-rs Rust crate for this post. So I want you to visit its website and read its API and documenation first.
The chat app we will build here is just the improved version of ws-rs-html-example. Therefore, I want you to visit it and read its source code.
Whenever you have doubt about Rust, please visit Rust Documentation page and serach on your own. It will be better for you to read Concurrency in Rust and search other articles if you want to understand why Rust is fast.
[Table of Contents]
- Setup Rocket to serve files
- ws-rs for socket server
- HTML and CSS for layout
1. Setup Rocket to serve files
(You can skip this part if you already downloaded GitHub Respoitory and understand how to structure Rust application.)
If you have tested code at ws-rs-html-example before you read on, you should have found that a single Rust(.rs) file does everything to render html, serve file, and exchange messages.
It may be a decent single file example but it will be difficult to build more complicated app later. Therefore, we will pass its role to serve files to Rocket web framework. I prefer Rocket for it has many examples but you may use whatever framework.
We can start this from our Cargo.toml file like the code snippet below or use $cargo add ws-rs rocket.(You can visit cargo-edit page for this command)
Then, ws-rs crate to work as socket server to handle chat messages.
Then we will build main.rs file first to be starting point for our Rust app.(Please, refer to the repository I gave before whenever you have doubts.)
The major part of the Rocket relevant code will be the boilerplate if you want to write minimum webpage with it. So you don’t have to understand all at once.
But the important points here are
- We use thread to separate chat server and not to affect(break) the main server that manages your website(It is Rocket here)
- You can assign .stack_size(83886 * 1024) here if you want to be serious with your chat app later.(You can search “How many resources chat app need” at your search engine.)
The part of the code snippet above includes
They are to serve routes and init your app with them.
The important part here will be static_files and ws_rs.
When you see the source code for static_routes first,
It is just to serve every files in static folder. You can just copy and paste it when you need to serve every files in static folder.
(You can use simplified API in newer version of Rocket if you want.)
for ws_rs route, important part is
and it is to serve HTML files for chat app.
For example, https://www.yourwebsite.com/chat
2. ws-rs for socket server
In this part, we will learn how to build server socket with Rust.
The code snippet is a little bit long but the important parts will be
- You need on_request part just once and you don’t have to reconnect later.
- Use them to verify what you can do when the first socket connection between server and client happen and read the documenation for them
- We need to count how many connections there are because it affects connection quality. You may use the
number_of_connectionvariable with conditional statement.(We will write code for that in client side later. You may use your own code.)
- This is the most important part. Even though we use localhost first and not real users, there should be some ways to differenciate the users from one another. So We use value of &handshake.perr_addr.unwrap() for the purpose and also number_of_connection inside
fn on_open. (If you open various windows for http://localhost:8000/chat later, You can see that it always return different values in your CLI.)
- This is where you can do various things with messages from users. You can use database to save messages from users here. You may write experimental code, for example, to send warning received from other users to everyone connected to the server socket.(You may test it with !warn in socket client later.)
self.out.broadcast(message)used to send messages to all users. It is the last API used before the messages from the server arrive to clients connected to socket.
self.count.set(self.count.get() - 1)is used to recalculate the total number of user when some client close the connection.
(It is important to think that Frontend and Backend code all in one.)
3. HTML and CSS for Layout
We briefly learnt the Rust serverside code to build our chat app. It is time to build Frontend part to help users.
If you see the index.html file, The important part will be
The main points here are
- They are CSS files for layout. You can edit or use your own if you want.
- The chat message will be written here inside
<li>wrappers and it is important to know that they are under
(steadylearner.css above is especially used for React and prop-passer package that I wrote, it is just the bunch of class names that does one thing at a time. I want you not to be confused with many CSS classes when you see the source code. You can verify how they work better at Steadylearner)
You can test this layout in React version at CodeSandbox also.
React prop-passer example with Rust Chat App Layout - CodeSandbox
This is to show how to use prop-passer with the code used for…
I made it to show how to use prop-passer to extract common props and reduce the size of app in total.
So it will not be perfect and will take time to load because React App is much heavier in size to load evert dependencies. But it will be better than start from nothing.
Please, verify it at full size window also because the purpose of this app is not to make it responsive and perfect but just to show that you can make Rust chat app.
If you already have experience with chat app, The part 1. and 2. is already sufficient for you to start your Rust chat app.
So before you read on, I want you to know the two points.
- I haven’t written code for chat app before this post. So please use this just for reference.
- I decided not to use Frontend Frameworks here because I wanted to find that I can write something useful without them.
Therefore, the code below may not be well-organized and want you to use framework if you want to make it advanced with database, login, send and receive video and image etc.
The index.js file we will use will be similar to the code below.
The code snippet is a little bit long and I will explain only important parts here.
- We import modules you need later to use emojis in your chat app and connect your client to the web socket server with
- We assign roles for HTML code with id clear and exit we wrote in index.html before. It won’t be difficult to understand what they do and you can find the codes that does similar things in the next.
- We find HTMLelement with id form with
document.getElementById. Then we define what should happen when users type to it. We save the user input with time( userInputs.push(userInputWithTime);) and send it to the server with
socket.send.(You can see that you can write some features before user input is sent to the socket server such as "clear" and "exit" here.)
- Use this part to allow users to type emojis easily. Please, read the doucmenation for them.( node-emoji, has-emoji)
- When socket closes, we notify users that the socket connection is closed and save messages from the user, other users and server to the localStorage.(You can use your database API instead.)
You can modify and bundle them with Browserify
$browserify index.js > bundle.js after you install them with
$sudo npm install -g browserify.
Then you can run your chat app with
$cargo run and verify the result and test them with various windows open while you type commands defined here and click the components.
I hope the post was helpful to start your own chat app with Rust. It may not be sufficient to call it complete chat application. But it would be a starting point to write chat app with Rust.
(I would be grateful also if someone give me a chance to know somone who can help me to imporve Rust code skill for it is difficult to find one here.)
We might learn how to write Rust code for Frontend and Backend code later with this example.
Thanks and please share this post with others
(Originally published at http://www.steadylearner.com/blog)