当前位置: 代码迷 >> 综合 >> Rust: Tcp 服务器与客户端的一个简单例子
  详细解决方案

Rust: Tcp 服务器与客户端的一个简单例子

热度:74   发布时间:2023-12-12 15:21:43.0

Rust: Tcp 服务器与客户端的一个简单例子

废话不多讲,直接上栗子:

1 服务器端代码

use std ::net::{
    TcpListener,TcpStream};
use std::thread;
use std::time;
use std::io;
use std::io::{
    Read,Write};fn handle_client(mut stream: TcpStream) -> io::Result<()>{
    let mut buf = [0;512];for _ in 0..1000{
    let bytes_read = stream.read(&mut buf)?;if bytes_read == 0{
    return Ok(());}stream.write(&buf[..bytes_read])?;thread::sleep(time::Duration::from_secs(1));}Ok(())
}fn main() -> io::Result<()>{
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();let mut thread_vec: Vec<thread::JoinHandle<()>> = Vec::new();for stream in listener.incoming() {
    let stream = stream.expect("failed");let handle = thread::spawn(move || {
    handle_client(stream).unwrap_or_else(|error| eprintln!("{:?}",error))});thread_vec.push(handle);}for handle in thread_vec {
    handle.join().unwrap();}Ok(())
}

2 客户端

use std::io::{
    self,prelude::*,BufReader,Write};
use std::net::TcpStream;
use std::str;fn main() -> io::Result<( )> {
    let mut stream = TcpStream::connect("127.0.0.1:8080")?;for i in 0..3 {
    println!("i = {}", i);let mut input = String::new();println!("read_line");io::stdin().read_line(&mut input).expect("Failed to read");println!("write");stream.write(input.as_bytes()).expect("failed to write");println!("BufReader::new())");let mut reader =BufReader::new(&stream);let mut buffer: Vec<u8> = Vec::new();println!("read_until");reader.read_until(b'\n',&mut buffer)?;println!("read form server:{}",str::from_utf8(&buffer).unwrap());println!("");}Ok(())
}