惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
月光博客
月光博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Hugging Face - Blog
Hugging Face - Blog
Project Zero
Project Zero
博客园 - 叶小钗
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
L
LINUX DO - 最新话题
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
I
InfoQ
F
Fortinet All Blogs
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
T
Tenable Blog
B
Blog RSS Feed

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone Object streams in Node.js
Tokio: Getting Started
2024-11-18 · via oida.dev | TypeScript, Rust

Let’s get started with our first Tokio app. Create a new project using Cargo and add the tokio dependency either to your Cargo.toml file or directly on the command line.

$ cargo add tokio --features full

Tokio comes with a ton of features, and for the scope of this guide, we just add all of them. In a real production app, you would switch features on and off as needed.

Hello Tokio #

This is what a Tokio “Hello, World!” app with some basic network I/O looks like:

use tokio::{
io::{self, AsyncWriteExt},
net::TcpListener,
};

#[tokio::main] // (1)
async fn main() -> io::Result<()> {
let listener = TcpListener::bind("localhost:8001").await?; // (2)
loop {
let (mut socket, addr) = listener.accept().await?;
println!("Listening to {}", addr);
tokio::spawn(async move { // (3)
socket.write_all("Hello World!\n\r".as_bytes()).await
});
}
}

The application creates a TCP Server and listens to port 8001. It waits for incoming connections, and when it got one, it will write “Hello, World” to the client.

It’s just a few lines of code, but there are already some new concepts going on. Let’s break them down piece by piece.

1. The #[tokio::main] attribute macro #

The first thing that you’ll notice is that we don’t work with a regular main function, but rather have an async main().

#[tokio::main]
async fn main() {
println!("Hello, world!");
}

At the time of writing, Rust won’t recognize this and won’t support this entry point. The #[tokio::main] attribute macro makes this work. It creates a real main function and sets up a default Tokio runtime. If you expand the macro, it may look something like this:

fn main() {
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
println!("Hello, world!");
});
}

In reality there a bit more details, but you get the gist. It creates a new, multi-threaded runtime and blocks with the Future from the async fn main() that you provided earlier.

Every async function or block creates code that implements the Future trait. The Tokio runtime can take this Future and execute it concurrently with other tasks. To kick off the process, it will execute the main entry point as “blocking”. This means that it will wait for the Future to complete before it exits the program. All other Futures and tasks that are spawned within this main entry point are then executed concurrently.

2. TCP Listeners #

Next, we create a TcpListener and bind it to localhost:8001.

let listener = TcpListener::bind("localhost:8001").await?;
loop {
let (mut socket, addr) = listener.accept().await?;
// ...
}

This code is equivalent to the sync version that you can find in the standard library of Rust. Tokio includes async versions of many standard library types, and try to keep the same API as the original. In the net feature, you will get abstractions for network applications, Tokio’s strength and main use case. It’s also possible to convert std::net::TcpListeners to tokio listeners. In the next line, we loop and accept listener connections.

3. Spawning tasks #

Spawning tasks is similar to spawning threads.

tokio::spawn(async move {
socket.write_all("Hello World!\n\r".as_bytes()).await
});

Tokio’s spawn function takes everything that implements a proper Future. This can be async blocks or functions, or anything that implements the Future trait. In this example we spawn an async block with a move closure. Just like in Rust with threads, this move keywords transfers ownership of all variables into the closure.

Tasks are Tokio’s unit of execution. You should be able to spawn thousands, if not millions of tasks. tokio::spawn submits tasks to Tokio’s scheduler. The way Tokio works, it will pick a task that is ready to work with from a task queue, runs it on the worker thread until it hits an .await point, puts it back on the queue and continues once the Future is ready to continue.

Like thread::spawn, tokio::spawn returns a JoinHandle that can be .await-ed.

Trait bounds #

Tasks are are ‘static bound. They must not contain any references to data owned outside the task. Use move closures to transfer ownership to async blocks.

Tasks are Send bound. This allows Tokio to move tasks between threads. Tasks are Send when all data that is held across .await calls is Send.

Other spawning methods #

spawn_blocking runs the provided closure on a thread where blocking is acceptable. A closure that is run through this method runs on a dedicated thread pool for blocking tasks without holding up the main futures executor.

spawn_local spawns a !Send future on the local task set. The spawned future will be run on the same thread.

Exercise 1: Create an echo server #

With the knowledge from this chapter, try to create an echo server with Tokio. The server should listen on localhost:8001 and echo back any message it receives. Make sure that the server:

  1. Accepts incoming connections
  2. Reads incoming messages
  3. Writes the message back to the client

As a stretch goal, try to handle multiple clients concurrently (Don’t worry if not, we take of that in the next chapter). Use telnet localhost 8001 to test your server (or use the demo client).

Solution #

This is the solution for the echo server exercise:

use tokio::{
io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader},
net::TcpListener,
};

#[tokio::main]
async fn main() -> io::Result<()> {
let listener = TcpListener::bind("localhost:8001").await?; // (1)
loop {
let (mut socket, addr) = listener.accept().await?; // (2)
println!("New connection at {}", addr);
tokio::spawn(async move { // (3)
let (reader, mut writer) = socket.split(); // (4)
let mut buf = String::new();
let mut reader = BufReader::new(reader); // (5)

// (6)
while let Ok(_b_read) = reader.read_line(&mut buf).await {
if buf.trim() == "quit" { // (7)
break;
}
writer.write_all(buf.as_bytes()).await.unwrap(); // (8)
buf.clear();
}
});
}
}

A quick rundown:

  1. Just like in the “Tokio Hello World” example, we create a listener on port 8001.
  2. We accept incoming connections in a loop.
  3. For each connection, we spawn a new task. With this line, we are able to defer the work into a separate task. The main loop can continue to accept new connections. The move keyword makes sure that the task takes ownership of the socket.
  4. We split the socket into a reader and a writer. We read incoming messages from the reader and write messages back to the writer. All over the same socket.
  5. An empty string and a BufReader help us to read lines from the reader. The BufReader comes from tokio::io, has a similar interface to the standard library’s BufReader, but is async and can work with Tokio’s socket abstraction.
  6. We read lines from the reader in a loop. This loop will continue until the client sends an empty message. read_line is available if you import the AsyncBufReadExt trait.
  7. If the client sends the text “quit”, we break out of the loop.
  8. We write the message back to the client. write_all is available if you import the AsyncWriteExt trait. We call unwrap at this point. Should this fail, the current thread panics. In Tokio, this means that the current worker thread panics. This does not influence the other worker threads. The Tokio runtime will also respawn a new worker thread if this panic happens. So even if we want to avoid unwraps and subsequent panics, for our little example in this context, it’s fine.

Tokio: Table of contents

  1. Getting Started
  2. Channels
  3. Macros

Related Articles