src/concurrency/async-exercises/chat-app.md
In this exercise, we want to use our new knowledge to implement a broadcast chat application. We have a chat server that the clients connect to and publish their messages. The client reads user messages from the standard input, and sends them to the server. The chat server broadcasts each message that it receives to all the clients.
For this, we use a broadcast channel on the server, and
tokio_websockets for the communication between the client and the server.
Create a new Cargo project and add the following dependencies:
Cargo.toml:
<!-- File Cargo.toml -->{{#include chat-async/Cargo.toml}}
You are going to need the following functions from tokio and
tokio_websockets. Take time to familiarize yourself with the API.
WebSocketStream: for asynchronously
reading messages from a Websocket Stream.WebSocketStream: for asynchronously
sending messages on a Websocket Stream.Normally in a Cargo project, you can have only one binary, and one src/main.rs
file. In this project, we need two binaries. One for the client, and one for the
server. You could potentially make them two separate Cargo projects, but we are
going to put them in a single Cargo project with two binaries. For this to work,
the client and the server code should go under src/bin (see the
documentation).
Copy the following server and client code into src/bin/server.rs and
src/bin/client.rs, respectively. Your task is to complete these files as
described below.
src/bin/server.rs:
<!-- File src/bin/server.rs --># // Copyright 2024 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
{{#include chat-async/src/bin/server.rs:setup}}
{{#include chat-async/src/bin/server.rs:handle_connection}}
// TODO: For a hint, see the description of the task below.
{{#include chat-async/src/bin/server.rs:main}}
src/bin/client.rs:
<!-- File src/bin/client.rs --># // Copyright 2024 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
{{#include chat-async/src/bin/client.rs:setup}}
// TODO: For a hint, see the description of the task below.
}
Run the server with:
cargo run --bin server
and the client with:
cargo run --bin client
handle_connection function in src/bin/server.rs.
tokio::select! for concurrently performing two tasks in a
continuous loop. One task receives messages from the client and broadcasts
them. The other sends messages received by the server to the client.src/bin/client.rs.
tokio::select! in a continuous loop for concurrently
performing two tasks: (1) reading user messages from standard input and
sending them to the server, and (2) receiving messages from the server, and
displaying them for the user.