CentOS 配置 Rust 的网络环境
一 基础网络连通与开发工具
ip addr、ip routeping -c 4 8.8.8.8nslookup www.rust-lang.orgsudo yum install -y gcc make openssl-develsudo dnf install -y gcc make openssl-develcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource "$HOME/.cargo/env"rustc -V、cargo -V二 提升下载速度 国内镜像与代理
echo 'export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static' | sudo tee -a /etc/profile
echo 'export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup' | sudo tee -a /etc/profile
source /etc/profile
~/.bashrc 或 ~/.zshrc 中添加相同两行并 source 对应文件。${HOME}/.cargo/config[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
registry = "git://mirrors.ustc.edu.cn/crates.io-index"
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
${HOME}/.cargo/config:[http]
proxy = "http://proxy.example.com:8080"
[https]
proxy = "http://proxy.example.com:8080"
unset HTTP_PROXY HTTPS_PROXY。三 编写与运行一个网络程序
cargo new rust_echo && cd rust_echoCargo.toml:[dependencies]
tokio = { version = "1", features = ["full"] }
src/main.rs:use tokio::net::{TcpListener, TcpStream};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind("0.0.0.0:8080").await?;
println!("Server listening on 0.0.0.0:8080");
loop {
let (mut socket, addr) = listener.accept().await?;
println!("New connection from {:?}", addr);
tokio::spawn(async move {
let mut buf = vec![0; 1024];
loop {
match socket.read(&mut buf).await {
Ok(0) => return, // 对端关闭
Ok(n) => {
if let Err(e) = socket.write_all(&buf[..n]).await {
eprintln!("write error: {:?}", e);
return;
}
}
Err(e) => {
eprintln!("read error: {:?}", e);
return;
}
}
}
});
}
}
cargo runnc -vz 127.0.0.1 8080 或 telnet 127.0.0.1 8080nc -vz <服务器IP> 8080sudo firewall-cmd --add-port=8080/tcp --permanent && sudo firewall-cmd --reload四 常见问题与排错
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
[source.crates-io]
registry = "sparse+https://github.com/rust-lang/crates.io-index"
git config --global http.proxy http://proxy.example.com:8080git config --global --unset http.proxy[http]/[https] 段落设置代理(见上文)。sudo yum/dnf install -y gcc make openssl-develss -ltnp | grep 8080sudo kill -9 <PID>source "$HOME/.cargo/env" 或重登会话。