您的位置:首页 >如何用Rust实现Linux下的网络编程
发布于2026-04-24 阅读(0)
扫一扫,手机访问
想在Linux系统里用Rust搞网络编程?这事儿其实没想象中那么复杂。Rust标准库里的std::net模块已经为我们准备好了不少基础工具,从TCP到UDP都能覆盖。下面咱们就从一个最经典的例子入手——搭建一个能“回声”的TCP服务器和客户端,把整个流程走一遍。

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
let bytes_read = match stream.read(&mut buffer) {
Ok(bytes) => bytes,
Err(_) => return,
};
// If we got no bytes, we've reached the end of the stream.
if bytes_read == 0 { return; }
// Write the data back to the socket.
if let Err(_) = stream.write_all(&buffer[..bytes_read]) {
return;
}
}
}
fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:7878")?;
// Listen for incoming connections.
for stream in listener.incoming() {
match stream {
Ok(stream) => {
// Spawn a new thread to handle the connection.
thread::spawn(|| handle_client(stream));
}
Err(err) => {
println!("Error: {}", err);
}
}
}
Ok(())
}
use std::io::{Read, Write};
use std::net::TcpStream;
fn main() -> std::io::Result<()> {
let mut stream = TcpStream::connect("127.0.0.1:7878")?;
// Send a message to the server.
let msg = "Hello, world!";
stream.write_all(msg.as_bytes())?;
// Read the server's response.
let mut buffer = [0; 1024];
let bytes_read = stream.read(&mut buffer)?;
println!("Received: {}", String::from_utf8_lossy(&buffer[..bytes_read]));
Ok(())
}
整个流程其实很清晰:服务器在本地7878端口竖起“耳朵”监听,一旦有客户端敲门,它就立刻派一个新线程去接待,并把收到的任何话原封不动地“说”回去。客户端呢,就是连接、发送一句“Hello, world!”,然后等着听那个熟悉的回声。
动手试试看。先运行服务器程序,让它进入监听状态,然后再启动客户端。如果一切顺利,你会在客户端的终端里看到自己发出去的那句问候——这意味着一次完整的本地网络对话已经成功了。
当然,这只是一个起点。真实的网络世界要复杂得多:可能需要处理自定义的应用层协议,错误处理要更健壮,性能要求高了还得考虑异步I/O。说到异步,社区里tokio这类库已经非常成熟,它提供的异步运行时、定时器和任务调度器,正是构建高性能网络服务的得力助手。不过,那就是另一个更精彩的故事了。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9