在Rust中實(shí)現(xiàn)Linux網(wǎng)絡(luò)編程,你可以使用標(biāo)準(zhǔn)庫中的std::net
模塊
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
match stream.read(&mut buffer) {
Ok(_) => {
println!("接收到客戶端的數(shù)據(jù): {}", String::from_utf8_lossy(&buffer[..]));
stream.write(b"Hello from server!").unwrap();
}
Err(e) => println!("無法讀取客戶端數(shù)據(jù): {}", e),
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
println!("服務(wù)器已啟動(dòng),監(jiān)聽端口7878");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream);
});
}
Err(e) => println!("無法接受客戶端連接: {}", e),
}
}
}
use std::io::{Read, Write};
use std::net::TcpStream;
fn main() {
let mut stream = TcpStream::connect("127.0.0.1:7878").unwrap();
println!("已連接到服務(wù)器");
stream.write(b"Hello from client!").unwrap();
let mut buffer = [0; 1024];
match stream.read(&mut buffer) {
Ok(_) => {
println!("接收到服務(wù)器的數(shù)據(jù): {}", String::from_utf8_lossy(&buffer[..]));
}
Err(e) => println!("無法讀取服務(wù)器數(shù)據(jù): {}", e),
}
}
這些示例展示了如何使用Rust的std::net
模塊創(chuàng)建一個(gè)簡(jiǎn)單的TCP服務(wù)器和客戶端。你可以根據(jù)需要修改這些示例以滿足你的需求,例如使用UDP協(xié)議、實(shí)現(xiàn)更復(fù)雜的數(shù)據(jù)處理邏輯等。